Golang: Array

By Xah Lee. Date: . Last updated: .

Array is a fixed number of slots that hold values of the same type.

Syntax of Array Type

[n]type
Syntax to specify a array of n slots, each is of type type.
Array cannot be resized. Example: var x [10]int, 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 and initialize a array at the same time.
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 named arr.

Set Element

arr[n] = val
Set index n to val of array named arr.

Length

len(arr)
Return the number of slots.

Capacity

cap(arr)
Return the capacity.

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 _.

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

[see Golang: loop]

Print Array

fmt.Printf("%v\n", array)
Print array in human readable form
fmt.Printf("%#v\n", array)
Print array in golang syntax

To print each member on a line, you have write a loop.

[see Golang: loop]

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

}

Reference

The Go Programming Language Specification - The Go Programming Language#Array_types

Golang

Examples

Reference