In Go, arrays are a collection of elements of the same type. They are not as flexible as slices, but they provide a fixed-size list of elements with better performance characteristics because their size is determined at compile-time. Let's explore how to declare and initialize arrays in Go from basic to advanced levels.
Basic Array Declaration
To declare an array in Go, you use the syntax [n]Type, where n is the number of elements in the array, and Type is the data type of the elements. You can declare an uninitialized array that defaults to zero values.
package main
import "fmt"
func main() {
var arr [5]int // declare an array of 5 integers
fmt.Println(arr) // Output: [0 0 0 0 0]
}
Intermediate Array Initialization
You can also declare and initialize arrays at the same time using array literals. This method allows you to specify the array values within curly braces.
package main
import "fmt"
func main() {
arr := [5]int{1, 2, 3, 4, 5} // declare and initialize
fmt.Println(arr) // Output: [1 2 3 4 5]
arr2 := [...]int{10, 20, 30} // Compiler counts number of elements
fmt.Println(arr2) // Output: [10 20 30]
}
Using Array with Different Data Types
Arrays in Go can contain types other than int, such as string or float.
package main
import "fmt"
func main() {
var strArr [3]string
strArr[0] = "Hello"
strArr[1] = "World"
strArr[2] = "Go"
fmt.Println(strArr) // Output: [Hello World Go]
floatArr := [2]float64{1.5, 2.5}
fmt.Println(floatArr) // Output: [1.5 2.5]
}
Advanced Array Operations
As you gain more advanced expertise in Go, you may need to work with multidimensional arrays, commonly known as matrixes.
package main
import "fmt"
func main() {
// Declare a 2x3 integer array
var matrix [2][3]int
matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[1][0] = 4
matrix[1][1] = 5
matrix[1][2] = 6
fmt.Println(matrix) // Output: [[1 2 3] [4 5 6]]
// Or directly with initialization
initMatrix := [2][2]int{{1, 2}, {3, 4}}
fmt.Println(initMatrix) // Output: [[1 2] [3 4]]
}
Remember, with arrays, the size is part of the type, so [3]int and [5]int are different types. Arrays have fixed sizes so once an array of length 5 is declared, it cannot be resized.
By understanding how arrays work in Go, you can effectively use them for fixed-size data structures while benefiting from Go's performance characteristics.