Go Arrays

Fixed-size collections of elements in Go

📊 What are Go Arrays?

Arrays in Go are fixed-size collections that store elements of the same type. They provide a way to group related data together with a predetermined length that cannot be changed.


// Declare and initialize an array
var numbers [5]int = [5]int{1, 2, 3, 4, 5}
fmt.Println(numbers) // Output: [1 2 3 4 5]
                                    

Output:

[1 2 3 4 5]

Key Array Concepts

📏

Fixed Size

Arrays have a fixed length set at declaration

var arr [3]string // Size is 3
🔢

Zero-Indexed

Array elements start from index 0

arr[0] = "first"  // First element
arr[1] = "second" // Second element
🎯

Same Type

All elements must be the same data type

var ages [4]int    // Only integers
var names [3]string // Only strings

Fast Access

Direct access to elements by index

value := arr[2] // Get third element

🔹 Array Declaration

There are several ways to declare and initialize arrays in Go:

// Method 1: Declare then assign
var fruits [3]string
fruits[0] = "apple"
fruits[1] = "banana"
fruits[2] = "orange"

// Method 2: Declare and initialize
var colors [3]string = [3]string{"red", "green", "blue"}

// Method 3: Short declaration
numbers := [4]int{10, 20, 30, 40}

// Method 4: Let Go count the elements
scores := [...]int{95, 87, 92, 78, 85}

Output:

fruits: [apple banana orange]
colors: [red green blue]
numbers: [10 20 30 40]
scores: [95 87 92 78 85]

🔹 Accessing Array Elements

Use square brackets with the index to access or modify elements:

package main

import "fmt"

func main() {
    // Create an array
    grades := [5]int{85, 92, 78, 96, 88}
    
    // Access elements
    fmt.Println("First grade:", grades[0])
    fmt.Println("Last grade:", grades[4])
    
    // Modify an element
    grades[2] = 82
    fmt.Println("Updated grades:", grades)
    
    // Get array length
    fmt.Println("Number of grades:", len(grades))
}

Output:

First grade: 85
Last grade: 88
Updated grades: [85 92 82 96 88]
Number of grades: 5

🔹 Looping Through Arrays

Use for loops to iterate through array elements:

package main

import "fmt"

func main() {
    cities := [4]string{"New York", "London", "Tokyo", "Paris"}
    
    // Method 1: Traditional for loop
    fmt.Println("Method 1:")
    for i := 0; i < len(cities); i++ {
        fmt.Printf("City %d: %s\n", i+1, cities[i])
    }
    
    // Method 2: Range loop
    fmt.Println("\nMethod 2:")
    for index, city := range cities {
        fmt.Printf("Index %d: %s\n", index, city)
    }
    
    // Method 3: Range loop (values only)
    fmt.Println("\nMethod 3:")
    for _, city := range cities {
        fmt.Println("City:", city)
    }
}

Output:

Method 1:
City 1: New York
City 2: London
City 3: Tokyo
City 4: Paris

Method 2:
Index 0: New York
Index 1: London
Index 2: Tokyo
Index 3: Paris

Method 3:
City: New York
City: London
City: Tokyo
City: Paris

🧠 Test Your Knowledge

What is the index of the first element in a Go array?