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 = [3]int{5, 9, 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]

Print Array

To print each member on a line, you have to do a loop.

[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. Pointer
  22. String as Chars
  23. regexp
  24. Read File
  25. Write to File
  26. Walk Dir
  27. Check File Exist
  28. System Call
  29. Get Script Path
  30. Pointer
  31. Defer
  32. Random Number

Examples

  1. Match Any Regexp
  2. Find Replace
  3. Validate Links
  4. Generate Sitemap

Reference

  1. Go Spec