Golang Array

Last Updated: September 13, 2022

Go Array Syntax

var array_name [size_of_array]data_type

Go Programming Language for Dummies

Elements in arrays in Go are zero-based

package main

import "fmt"

func main() {

    marks := [4]int{56, 78, 98, 93} // short hand declaration to create array

    // marks := [...]int{56, 78, 98, 93} 
    // you can use this too

    fmt.Printf("%v", marks)

}

Declare empty array in GO

var days = [7] string

Assign a value to an array

days[0] ="Sunday"

Get the length of an array => len(days)

The index of an array starts from 0 and ends at length - 1

Array copy in GO

When you normally copy array a to b, it creates a new array for b

a := [4]int{56, 78, 98, 93}
var b = a
b[0] = 10
fmt.Printf("%v\n", a) // [56 78 98 93]
fmt.Printf("%v\n", b) // [10 78 98 93]

You can use the pointers to copy the array. So both a and b point to the same array

a := [4]int{56, 78, 98, 93}
var b = &a
b[0] = 10
fmt.Printf("%v\n", a) // [10 78 98 93]
fmt.Printf("%v\n", b) // [10 78 98 93]
Test