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 Literal Expression

This lets you declare and initialize a array at the same time. e.g.

var x = [4]int{5, 3, 2}

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

if you don't need the index or value, name the variable as _.

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

[see Golang: loop]

Slice

Slice is like a array, but length can change.

Slice is implemented on top of array, with almost no cost.

Most of the time, you want to use slice instead.

[see Golang: Slice]

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. Comment
  4. Print
  5. String
  6. Rune
  7. Variable
  8. Zero Value
  9. Constant
  10. If Then Else
  11. Switch/Case
  12. Loop
  13. Basic Types
  14. Array
  15. Slice
  16. Map
  17. Struct
  18. Function
  19. regexp
  20. Read File
  21. Write to File
  22. Walk Dir
  23. Check File Exist
  24. System Call
  25. Get Script Path
  26. Pointer
  27. Defer
  28. Random Number

Examples

  1. match any regexp
  2. Validate Links
  3. Generate Sitemap

Reference

  1. Go Spec