Arrays in Golang

Arrays in Golang

Array

An array is a homogeneous (fix type) data structure and it has fixed length. The type of array can be anything like integers, string or self-defined type.

  • An items in an array can be accessed through their index, and starts with zero.
  • The number of items in the array is called the length or size of the array.
  • Size of array is fixed and must be declared in the declaration of any array variable.

Syntax :-

var identifier [len]type

Example :-

var arr [5]int

Example of array in Golang

package main

import "fmt"

func main() {
    var x [5]int
    var i, j int

    for i = 0; i < 5; i++ {
        x[i] = i + 10
    }
    for j = 0; j < 5; j++ {
        fmt.Println("Element [", j, "] = ", x[j])
    }
}

Output

image.png

Multidimensional Arrays in Golang

Multidimensional array is a list of one-dimensional array

Syntax

var arr [x][y] type

Example :-

a = [3][4]int

Example of Multi-Dimensional array in Golang

package main

import "fmt"

func main() {
    var arr = [3][3]int{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    }
    var i, j int

    for i = 0; i < 3; i++ {
        for j = 0; j < 3; j++ {
            fmt.Print(arr[i][j])
        }
        fmt.Println()
    }
}

Output

image.png

Golang array is 0 indexed array like java.

Did you find this article valuable?

Support Gautam Jha by becoming a sponsor. Any amount is appreciated!