Golang: Array

By Xah Lee. Date: . Last updated: .

What is Array

Array is a ordered sequence of fixed number of slots that hold values of the same type. (The number of slots cannot be changed once declared. If you want to change number of slots, use Slice. )

Syntax of Array Type

[n]type

Syntax to specify a array of n slots, each is of type type. [see Golang: Basic Types]

Example: var x [10]int, declares a array with 10 slots of type int.

package main

import "fmt"

func main() {
	var a [2]string
	a[0] = "cat"
	a[1] = "dog"
	fmt.Println(a) // [cat dog]
}

Array Literal Expression

var x = [3]int{5, 9, 2}

Declare array and give values.

var x = [...]int{5, 9, 2}

Let compiler figure out the number of items.

package main

import "fmt"

func main() {

	// literal expression to init array slots
	var x = [4]int{5, 3, 2, 9}

	fmt.Println(x) // [5 3 2 9]
}

Get Element

arr[n]

Get index n of array arr. First element has index 0.

Set Element

arr[n] = val

Set slot at index n to val of array arr.

Length

len(arr)

Return the number of slots.

Golang, data structure

Golang, array and slice