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)

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

Loop Thru Array

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

package main

import "fmt"

func main() {
    var arr = []string{"aa", "bb", "cc"}
    for i, x := range arr {
        fmt.Println(i, x)
    }
    // prints
    // 0 aa
    // 1 bb
    // 2 cc

}

Reference

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

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

Golang

  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
  13. read file
  14. Write to File
  15. Go Spec