Go - Array Example

In Go, an array is a numbered sequence of elements of a specific length.

In other words, an array is a collection of elements of a single data type. An array holds a fixed number of elements, and it cannot grow or shrink.

  • Elements of an array are accessed through indexes. 
  • The first index is 0. 
  • By default, empty arrays are initialized with zero values (0, 0.0, false, or "").

Go - declare and initialize an array

The following example shows how to initialize an array in Go.


package main

import "fmt"

func main() {

    var vals [2]int
    fmt.Println(vals)

    vals[0] = 1
    vals[1] = 2
    fmt.Println(vals)
}

Output:

[0 0]
[1 2]

Use below syntax to declare and initialize an array in one line:


package main

import "fmt"

func main() {

    b := [5]int{1, 2, 3, 4, 5}
    fmt.Println("dcl:", b)
}

Output:

[1 2 3 4 5]
[1 2 3 0 0]

Go - array literal

Golang has array literals; we can specify the elements of the array between {} brackets.

In the example, we define two arrays with array literals.


package main

import "fmt"

func main() {

    vals := [5]int{1, 2, 3, 4, 5}
    fmt.Println(vals)

    vals2 := [5]int{1, 2, 3}
    fmt.Println(vals2)
}

Output:

[1 2 3 4 5]
[1 2 3 0 0]

Go - array length

The length of the array is determined with the len() function.

In the example, we define an array of strings. We print the number of programming languages in the array.


package main

import "fmt"

func main() {

    progLangs := [5]string{ "C", "C++", "Java", "Python", "Go" }

    fmt.Println("There are", len(progLangs ), "programming languages in the array")
}

Output:

[1 2 3 4 5]
[1 2 3 0 0]

Go - array indexing

Arrays are accessed with their index.


package main

import "fmt"

func main() {

    var progLangs[5]string

    progLangs[0] = "C"
    progLangs[1] = "C++"
    progLangs[2] = "Java"
    progLangs[3] = "Python"
    progLangs[4] = "Go"

    fmt.Println(progLangs[0], progLangs[1])
    fmt.Println(progLangs)
}

Output:

C C++
[C C++ Java Python Go]

Comments