Golang: Array

By Xah Lee. Date: .

Here's example of declaring array.

[see Golang: Basic Datatypes]

arrays cannot be resized.

package main

import "fmt"

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

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)

package main

import "fmt"

func main() {
        // array of 4 slots of int
        var x [4]int

        // length
        fmt.Println(len(x)) // 4
}

array declare and init

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]
}

Reference

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