Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Introduction to Arrays in Go Programming

What is an Array?

An array is a collection of elements, each identified by an index or key. In Go, arrays are a fixed-size sequence of elements of the same type. Arrays are useful for storing multiple values in a single, organized data structure.

Declaring Arrays

To declare an array in Go, you specify the type of its elements and the number of elements it can hold. The syntax is:

var arrayName [size]Type

For example, to declare an array of 5 integers, you would write:

var numbers [5]int

Initializing Arrays

You can initialize an array during its declaration by providing the values in curly braces:

var numbers = [5]int{1, 2, 3, 4, 5}

If you do not provide values for all elements, the remaining elements will be set to the zero value for the array's element type:

var numbers = [5]int{1, 2}

This will initialize the first two elements to 1 and 2, and the remaining elements to 0.

Accessing Array Elements

You can access the elements of an array using the index, which starts at 0. For example:

numbers[0]

This will access the first element of the numbers array. You can assign a value to a specific element as well:

numbers[1] = 10

Iterating Over Arrays

To iterate over the elements of an array, you can use a for loop. Here is an example:

for i := 0; i < len(numbers); i++ {
    fmt.Println(numbers[i])
}
                    

You can also use the range keyword to iterate over arrays:

for index, value := range numbers {
    fmt.Println(index, value)
}
                    

Multidimensional Arrays

Go supports multidimensional arrays, which are arrays of arrays. Here is how you can declare a 2x3 array:

var matrix [2][3]int

You can initialize it as follows:

var matrix = [2][3]int{{1, 2, 3}, {4, 5, 6}}

Example: Working with Arrays

Here is a complete example that demonstrates the declaration, initialization, and iteration of an array:

package main

import "fmt"

func main() {
    // Declare and initialize an array
    var numbers = [5]int{1, 2, 3, 4, 5}

    // Access and modify an element
    numbers[2] = 10

    // Iterate over the array using a for loop
    for i := 0; i < len(numbers); i++ {
        fmt.Println(numbers[i])
    }

    // Iterate over the array using range
    for index, value := range numbers {
        fmt.Println(index, value)
    }
}
                    

This program will output:

1
2
10
4
5
0 1
1 2
2 10
3 4
4 5

Conclusion

Arrays are a fundamental data structure in Go that allow you to store and manipulate collections of data. Understanding how to declare, initialize, and iterate over arrays is essential for any Go programmer. In this tutorial, we covered the basics of arrays in Go, including declaration, initialization, accessing elements, and iterating through arrays.