Golang: Array

By Xah Lee. Date: . Last updated: .

What is Array

Array is a 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.

Loop Thru Array

for i, x := range myArray { fmt.Println(i, x) }

If you don't need the index or value, name the variable as _. Example: for _, x := range myArray { fmt.Println(x) }

Print Array

Convert Array to Slice

array[:]
Return a slice of array. The slice shares the array storage. [see Golang: Slice]
package main

import "fmt"

func main() {

	var arr = [2]int{3, 4}

	// create a slice
	var s = arr[:]

	// s is now of type slice of int
	fmt.Printf("%T\n", s) // []int

}

Convert Array to String

Use fmt.Sprintf, with verb %v or %#v.