Array assignment in Go

Array assignment in Go is very different from some other programming languages like Java, C/C+++...  When you assign an array to another array variable in C/C++ or Java, it will not create new copy of the array, the two array variables are referencing the same memory for array.

However in Go, Array in Go is considered as a value instead of a pointer like other programming languages. When assign an array variable to another array variable, it will create a copy of the first array, then assign it to the second array, which means the two array variables are referencing different memories. See the example below:

package main

import (
"fmt"
)

func main() {
var a [3]int = [...]int{1, 1, 1}
var b [3]int
b = a
b[0] = 2
b[1] = 2
b[2] = 2
fmt.Println(a)
fmt.Println(b)

}


The output is:
[1 1 1] [2 2 2]

This also applies to passing array to a function as parameters. It will also create a copy of array, then pass to function calls. 

This certainly makes array copying become much easier. However when you have a big array, it will also slow down your program due to the copying operation.

If you want to do the same like Java and C/C++ to make two array variables to point to the same array, you can do this in Go as well. You can create variable b as a array pointer using *[3]int, and then assign the address of b to a using &. This works similar to C/C++ syntax. Below is the example code:

package main

import (
"fmt"
)

func main() {
var a [3]int = [...]int{1, 1, 1}
var b *[3]int

b = &a
b[0] = 2
b[1] = 2
b[2] = 2

fmt.Println(a)
fmt.Println(b)

}

The output is:
[2 2 2] &[2 2 2]

So the value of array a is changed as well by changing values in b.


Comments

Popular posts from this blog

Basic understanding of TLS-PSK protocol

Differences between ASIC, ASSP and ASIP

Orthogonal instruction set