Arrays in Go

An array is a data structure that consists of a collection of elements of a single type or simply you can say a special variable, which can hold more than one value at a time. The values an array holds are called its elements or items. An array holds a specific number of elements, and it cannot grow or shrink. Different data types can be handled as elements in arrays such as Int, String, Boolean, and others. The index of the first element of any dimension of an array is 0, the index of the second element of any array dimension is 1, and so on.

import "fmt"

func main() {
    // declare an array
    var colors [3]string
    // assign values to array
    colors[0] = "Red"
    colors[1] = "Green"
    colors[2] = "Blue"
    // print all items in array
    // print on item of an array
    // declare and assign
    var numbers = [5]int{5, 4, 2, 1, 10}
    // print length of array
    fmt.Println("Number of colors:", len(colors))
    fmt.Println("Number of numbers:", len(numbers))

Initialize an Array with an Array Literal

x := [5]int{10, 20, 30, 40, 50}   // Intialized with values
    var y [5]int = [5]int{10, 20, 30} // Partial assignment