C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
For: We use a for-loop to iterate over the array's elements. In this kind of for-loop, we specify a start, end, and an iteration.
Len: An array has a length. With len() we access the count of its elements—all elements are counted.
LenIndexes: The array is indexed starting at 0. The last index is one less than the array's total length.
Golang program that uses array
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])
}
}
Output
10
20
30
Caution: This is slow. Using slices is faster. For small arrays, passing directly may be an effective approach.
Golang program that passes array as argument
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)
}
Output
5
10
15
In main: We take a full-range slice of the array. The slice contains all the elements in the four-element int array.
Golang program that uses slice of array, parameter
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[:])
}
Output
-1
0
10
100
Version 1: We use an array: we assign into the array's elements, and then read from the array at indexes.
Version 2: In this version of the code, we use a slice. We perform the same actions on the slice that we use on the array.
Result: The array program has a consistent performance advantage in Go 1.8. Using an array can lead to a significant speedup.
Note: If you remove the element assignments, there is less of a difference. So an array might be faster only if you are assigning elements.
Golang program that benchmarks array, slice
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))
}
Output
1.3679763s Array: [...]int
1.6191417s Slice: []int
Quote: A slice, once initialized, is always associated with an underlying array that holds its elements (Go Specification).