Golang: Array

By Xah Lee. Date: . Last updated: .

Here's example of declaring array.

[see Golang: Basic Datatypes]

Array 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

Golang Topics

  1. Compile, Run
  2. Package, Import
  3. Function
  4. Variable
  5. Constant
  6. If Then Else
  7. switch/case
  8. Loop
  9. Basic Types
  10. Array
  11. Slice
  12. map

If you have a question, put $5 at patreon and message me.