Arrays
An array is defined by: [n]<type>
, where (n) is the length of the array and<type>
is the stuff you want to store. To assign or index an element in thearray, you use square brackets:
var arr [10]int
arr[0] = 42
arr[1] = 13
fmt.Printf("The first element is %d\n", arr[0])
Array types like var arr [10]int
have a fixed size. The size is part of thetype. They can’t grow, because then they would have a different type. Alsoarrays are values: Assigning one array to another copies all the elements. Inparticular, if you pass an array to a function it will receive a copy of thearray, not a pointer to it.
To declare an array you can use the following: vara [3]int
. To initialize it to something other than zero, use acomposite literal a := [3]int{1, 2, 3}
. This can be shortened to a := […]int{1, 2, 3}
, where Go counts the elements automatically.
A composite literal allows youto assign a value directly to an array, slice, or map.See for more information.
When declaring arrays you always have to type something in between the squarebrackets, either a number or three dots (…
), when using a composite literal.When using multidimensional arrays, you can use the following syntax: a :=[2][2]int{ {1,2}, {3,4} }
. Now that you know about arrays you will be delightedto learn that you will almost never use them in Go, because there is somethingmuch more flexible: slices.