In Go, an array is a fixed-size collection of elements, all of the same type.
Arrays are useful for storing multiple values in a single variable, such as a list of numbers or strings.
While arrays are not as flexible as slices in Go, they’re useful for cases where you need a fixed-size collection of items.
In this tutorial, we’ll cover:
1. Declaring and Initializing Arrays
To declare an array in Go, specify the type and size (number of elements). You can initialize arrays with or without values.
package main import "fmt" func main() { // Declare an array of integers with size 5 var numbers [5]int fmt.Println("Empty array:", numbers) // Declare and initialize an array of strings var colors = [3]string{"red", "green", "blue"} fmt.Println("Colors:", colors) // Array with inferred length primes := [...]int{2, 3, 5, 7, 11} fmt.Println("Primes:", primes) }
Output:
Empty array: [0 0 0 0 0] Colors: [red green blue] Primes: [2 3 5 7 11]
In this example:
- numbers is an integer array with a fixed size of 5. Since it’s not initialized, it contains zero values (0 for integers).
- colors is a string array initialized with specific values.
- primes is an integer array with inferred size (…), based on the number of elements provided.
2. Accessing and Modifying Array Elements
You can access and modify array elements using their index. In Go, array indices start from 0.
package main import "fmt" func main() { // Declare and initialize an array var scores = [3]int{90, 85, 88} // Access elements by index fmt.Println("First score:", scores[0]) fmt.Println("Second score:", scores[1]) // Modify elements scores[1] = 95 fmt.Println("Modified scores:", scores) }
Output:
First score: 90 Second score: 85 Modified scores: [90 95 88]
In this example:
- scores[1] = 95 modifies the second element of the array from 85 to 95.
Note: Trying to access an index out of the array’s bounds will cause a runtime error.
3. Array Length and Looping Through Arrays
You can use the len() function to get the length of an array. Go also supports looping through arrays with a for loop or a for-range loop.
Using for loop
package main import "fmt" func main() { var numbers = [5]int{10, 20, 30, 40, 50} // Print array length fmt.Println("Array length:", len(numbers)) // Loop through array with index for i := 0; i < len(numbers); i++ { fmt.Println("Element at index", i, "is", numbers[i]) } }
Output:
Array length: 5 Element at index 0 is 10 Element at index 1 is 20 Element at index 2 is 30 Element at index 3 is 40 Element at index 4 is 50
Using for-range loop
The for-range loop iterates over each element in the array and provides both the index and value.
package main import "fmt" func main() { var fruits = [3]string{"apple", "banana", "cherry"} for index, fruit := range fruits { fmt.Println("Index:", index, "Fruit:", fruit) } }
Output:
Index: 0 Fruit: apple Index: 1 Fruit: banana Index: 2 Fruit: cherry
In this example:
- for index, fruit := range fruits allows you to loop through the array elements with both the index and value.
4. Multidimensional Arrays
Go supports multidimensional arrays, where each element in an array is another array. These arrays are useful for representing data in tables, matrices, or grids.
package main import "fmt" func main() { // Declare a 2x3 integer array (2 rows, 3 columns) var matrix = [2][3]int{ {1, 2, 3}, {4, 5, 6}, } fmt.Println("2D Array (Matrix):", matrix) // Access elements in a multidimensional array fmt.Println("Element at [0][1]:", matrix[0][1]) fmt.Println("Element at [1][2]:", matrix[1][2]) }
Output:
2D Array (Matrix): [[1 2 3] [4 5 6]] Element at [0][1]: 2 Element at [1][2]: 6
In this example:
- matrix is a 2×3 array (2 rows, 3 columns).
- matrix[0][1] accesses the element in the first row and second column (2).
5. Passing Arrays to Functions
In Go, arrays are passed to functions by value, meaning a copy of the array is passed. If you want to modify the original array, you need to pass a pointer to it.
Passing by Value
package main import "fmt" func doubleValues(arr [3]int) { for i := 0; i < len(arr); i++ { arr[i] *= 2 } fmt.Println("Inside function:", arr) } func main() { nums := [3]int{1, 2, 3} doubleValues(nums) fmt.Println("Outside function:", nums) }
Output:
Inside function: [2 4 6] Outside function: [1 2 3]
In this example:
- doubleValues modifies a copy of the array nums, leaving the original array unchanged.
Passing by Reference
package main import "fmt" func doubleValues(arr *[3]int) { for i := 0; i < len(arr); i++ { arr[i] *= 2 } } func main() { nums := [3]int{1, 2, 3} doubleValues(&nums) fmt.Println("Modified array:", nums) }
Output:
Modified array: [2 4 6]
In this example:
- doubleValues takes a pointer to the array (*[3]int), allowing it to modify the original array.
6. Best Practices with Arrays in Go
a) Use Slices Instead of Arrays When Possible
Arrays in Go have a fixed size and are less flexible. Slices, which are built on top of arrays, are more commonly used in Go because they allow dynamic resizing.
b) Use for-range for Iterating
Using for-range to iterate over arrays is more idiomatic and concise in Go, especially when you only need to access elements without modifying them.
c) Be Careful with Passing Arrays to Functions
Passing large arrays by value can be inefficient. If you need to modify an array inside a function, consider passing a pointer or using a slice.
d) Prefer Clear Names
Use descriptive names for arrays to clearly indicate the data they hold, especially in larger programs where multiple arrays might be present.
Summary
In this tutorial, we covered the basics of working with arrays in Go:
- Declaring and Initializing Arrays: Creating arrays with and without values.
- Accessing and Modifying Array Elements: Using indices to get and set array values.
- Array Length and Looping Through Arrays: Using len() and iterating with for and for-range.
- Multidimensional Arrays: Working with arrays that contain other arrays.
- Passing Arrays to Functions: Understanding pass-by-value and pass-by-reference with pointers.
- Best Practices with Arrays: Using idiomatic practices for better readability and performance.
While arrays are less commonly used directly in Go (slices are preferred for their flexibility), understanding arrays is foundational for working with slices and managing fixed-size collections of data in Go.