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

Examples

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

Reference

  1. Go Spec