In Go an array is defined by its type, its size and shape. There is no universal array, but many typed and sized arrays. We build methods that act on arrays.
Slices are more versatile and tend to be used more in Go programs. But arrays can still be useful if we have a fixed size of data.
Let us begin with a simple example that loops over an array of 3 ints. We use an array initializer to create a 3-element array. It contains the values 10, 20 and 30.
for
-loop to iterate over the array's elements. In this kind of for
-loop, we specify a start, end, and an iteration.len()
we access the count of its elements—all elements are counted.package main import "fmt" func main() { // Create an array of three ints. array := [...]int{10, 20, 30} // Loop over three ints and print them. for i := 0; i < len(array); i++ { fmt.Println(array[i]) } }10 20 30
We can pass an array (specified by both element count and type) to a method. Arrays are values. They are copied when passed to a method.
package main import "fmt" func display(values [3]int) { fmt.Println(values[0]) fmt.Println(values[1]) fmt.Println(values[2]) } func main() { v := [...]int{5, 10, 15} // Pass the entire array to a method. // ... This copies the array. display(v) }5 10 15
Usually we pass slices of arrays to methods—this avoids a copy of the elements. Here, display()
receives an int
array slice.
int
array.package main import "fmt" func display(values []int) { // Loop over slice argument and display elements. for i:= 0; i < len(values); i++ { fmt.Println(values[i]) } } func main() { // Create a four-element array. array := [...]int{-1, 0, 10, 100} // Pass a slice of the array to display. // ... This slice contains all elements. display(array[:]) }-1 0 10 100
Do arrays have a performance advantage over slices? Potentially, performance information could be used to optimize many programs.
package main import ( "fmt" "time" ) func main() { // Create array and slice. array := [...]int{10, 20, 30} slice := []int{10, 20, 30} sum := 0 t0 := time.Now() // Version 1: assign into and read array elements. for i := 0; i < 1000000000; i++ { sum = 0 for x := 0; x < len(array); x++ { array[x] = 5 sum += array[x] } if sum == 0 { break } } t1 := time.Now() // Version 2: assign into and read slice elements. for i := 0; i < 1000000000; i++ { sum = 0 for x := 0; x < len(slice); x++ { slice[x] = 5 sum += slice[x] } if sum == 0 { break } } t2 := time.Now() // Results. fmt.Println(t1.Sub(t0)) fmt.Println(t2.Sub(t1)) }1.3679763s Array: [...]int 1.6191417s Slice: []int
In Go programs, we typically use slices. But a slice is always based on an array. We can think of arrays as the underlying storage for slices.
Arrays are used as a building block, a foundation, of many things in languages. More complex collections can be built from arrays.