Go Arrays
Arrays are numbered, fixed-length sequences of elements of the same data type.
Arrays vs. Slices
Arrays differ from slices in that their size cannot be changed after being created.
Another difference is that an array is passed to a function as a copy of the array, whereas a slice is passed as a reference to the underlying array. This means that changes done to an array passed to a function will not be reflected outside that function, but changes done to a slice will affect the underlying array.
Syntax
There are two ways of creating an array:
- With the
varkeyword - With the
:=short assignment statement and curly brackets (with elements optionally listed within them)
var arr1 [n]type
arr2 := [n]type{el1, el2, ..., eln}
In both cases, n represents the capacity of the array and type is the desired type.
Note: Curly brackets are needed in the
:=assignment statement. Conversely, thevarkeyword does not allow them, meaning that element values cannot be set in the same line.
Examples
In the following example, two arrays, zeroes1 and zeroes2, are created without initial values. For arrays and slices in Go, numeric values are predefined as 0:
var zeroes1 [5]intzeroes2 := [3]float64{}fmt.Println(zeroes1)// Output: [0, 0, 0, 0, 0]fmt.Println(zeroes2)// Output: [0, 0, 0]
The next example sets the element values using the := assignment statement:
array := [3]string{"Hello", "World", "!"}fmt.Println(array)// Output: [Hello World !]
Accessing Elements
Array elements can be accessed using the array’s name followed by the element’s index in square brackets:
var array [3]intarray[0] = 1array[1] = 2array[2] = 3fmt.Println(array[0], array[1], array[2])// Output: 1 2 3
Multidimensional Arrays
Multidimensional arrays can be created and accessed similarly to the one-dimensional arrays.
It is possible to declare arrays of any number of dimensions with one of the following syntaxes:
var array [x1][x2]...[xn]type
array := [x1][x2]...[xn]type
x1, x2, ..., xnrepresents the capacities of each dimension.typeis the desired type of an array.
The following codebyte example creates a multidimensional array in two different ways and then accesses items within them:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Go on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn how to use Go (Golang), an open-source programming language supported by Google!
- Beginner Friendly.6 hours