Go by Example: Arrays https://gobyexample.
com/arrays
Go by Example: Arrays
In Go, an array is a numbered sequence of
elements of a specific length. In typical Go code,
slices are much more common; arrays are useful
in some special scenarios.
package main
import "fmt"
func main() {
Here we create an array a that will hold exactly 5 var a [5]int
ints. The type of elements and length are both fmt.Println("emp:", a)
part of the array’s type. By default an array is
zero-valued, which for ints means 0s.
We can set a value at an index using the a[4] = 100
array[index] = value syntax, and get a value with fmt.Println("set:", a)
array[index]. fmt.Println("get:", a[4])
The builtin len returns the length of an array. fmt.Println("len:", len(a))
Use this syntax to declare and initialize an array in b := [5]int{1, 2, 3, 4, 5}
one line. fmt.Println("dcl:", b)
You can also have the compiler count the number b = [...]int{1, 2, 3, 4, 5}
of elements for you with ... fmt.Println("dcl:", b)
If you specify the index with :, the elements in b = [...]int{100, 3: 400, 500}
between will be zeroed. fmt.Println("idx:", b)
Array types are one-dimensional, but you can var twoD [2][3]int
compose types to build multi-dimensional data for i := 0; i < 2; i++ {
structures. for j := 0; j < 3; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d: ", twoD)
You can create and initialize multi-dimensional twoD = [2][3]int{
arrays at once too. {1, 2, 3},
{1, 2, 3},
}
fmt.Println("2d: ", twoD)
}
Note that arrays appear in the form [v1 v2 v3 ...] $ go run arrays.go
when printed with fmt.Println. emp: [0 0 0 0 0]
set: [0 0 0 0 100]
get: 100
len: 5
dcl: [1 2 3 4 5]
dcl: [1 2 3 4 5]
idx: [100 0 0 400 500]
2d: [[0 1 2] [1 2 3]]
2d: [[1 2 3] [1 2 3]]
Next example: Slices.
by Mark McGranaghan and Eli Bendersky | source | license
1 of 1 11/26/24, 23:27