I want to explore something about how the memory is allocated when we try to copy a variable. I did some tests and this one confuses me:
func testArrayAddress() {
var a [3]int
b := a
fmt.Printf("address of a %p and of b %p \n", &(a[0]), &(b[0]))
}
The output is:
address of a 0xc8200126e0 and of b 0xc820012700
However as I assume a and b and pointing to the same array so the starting address of the first element should be the same?
This made me doubt that what happened when we exec the statement b := a
? Originally I thought it will just allocate one memory block for the array when we init variable a
, and b := a
makes b
pointing to the same memory location, but then it cannot explain why the address of the first element is not the same (which should be same element).
I changed the first line of code:
func testArrayAddress() {
var a = []int{1, 2, 3}
b := a
fmt.Printf("address of a's first element %p and of b %p \n", &(a[0]), &(b[0]))
}
Then the output is:
address of a's first element 0xc8200126e0 and of b 0xc8200126e0
It gives me the same result now.
The question I want to ask are:
In Golang when we do variable copy (
b := a
), are we also creating a copy of data in the memory? And is it the same for both immutable and mutable type?If we are copying for mutable type (eg. array) as well, how it manages to achieve modifying variable will also affects others (
a[0] = 42
will affectb[0]
)?How is
[]int
type different from[number]int
type which I tested in the last case?