golang arrays can hold multiple values. The minimum elements of an array is zero, but they usually have two or more. Each element in an array has a unique index.
The index starts at zero (0). That means to access the first element of an array, you need to use the zeroth index.
Arrays in golang
Introduction to arrays
An array is a set of numbered and length-fixed data item sequences that have the same unique type
This type can be any primitive type such as:
- integer
- string
- custom type
The array length must be a constant expression and must be a non-negative integer.
An array in the Go language is a type of value (not a pointer to the
first element in C/C++), so it can be created by new()
:
var arr1 = new([5]int)
The array element can be read (or modified) by an index (position), the index starts from 0, the first element index is 0, the second index is 1, and so on.
.Println(arr1[0]) // output first element fmt
Note The array starts at 0 in many programming languages, including Golang, C++, C, C# and Python
The number of elements, also known as length or array size, must be fixed and given when the array is declared (need to know the array length to allocate memory at compile time); the array length is up to 2 Gb.
If each element is an integer value, all elements are automatically initialized to the default value of 0 when the array is declared.
package main
import "fmt"
func main() {
var arr1 = new([5]int)
.Println(arr1[2])
fmt.Println(arr1[3])
fmt}
0
0
The method of traversing an array can either be a condition loop or a for-range can be used.Both of these structures are equally applicable to Slices.
Here is an array of non-fixed length that is determined by the number of elements specified at initialization time.
Several assignment modes:
var arrAge = [5]int{18, 20, 15, 22, 16}
var arrLazy = [...]int{5, 6, 7, 8, 22}
var arrKeyValue = [5]string{3: "Chris", 4: "Ron"}
Example
The program below is an example of an array loop in golang. The array we define has several elements. We print the first item with the zeroth index.
package main
import "fmt"
func main() {
var a = []int64{ 1,2,3,4 }
.Printf("First element %d", a[0] )
fmt.Printf("Second element %d", a[1] )
fmt}
Upon running this program it will output the first (1) and second (2) element of the array. They are referenced by the zeroth and first index. In short: computers start counting from 0.
This program will output:
First element: 1
Second element: 2
The index should not be larger than the array, that could throw an error or unexpected results.
Video tutorial
Video below
Exercises
- Create an array with the number 0 to 10
- Create an array of strings with names