Look at the following code snippet.
package main
import (
"fmt"
)
type class struct {
prop1 string
prop2 string
}
func main() {
va1 := &class{"Hello", "Foo"}
fmt.Println(&va1)
va1 = &class{"TOO", "Boo"}
fmt.Println(&va1)
}
As a result I've got the same pointed address.
0x1215a0c0
0x1215a0c0
With &T{} it will allocate new zeroed value address. But why here I've got the same address? Do I just override on second assignment the value?
The statement
fmt.Println(&va1)
prints the address of the variable va1
, not what va1
is pointing to. The address of the variable does not change.
Try this program:
va1 := &class{"Hello", "Foo"}
fmt.Printf("&va1: %v, pointer: %p, value: %v
", &va1, va1, va1)
va2 := va1
va1 = &class{"TOO", "Boo"}
fmt.Printf("&va1: %v, pointer: %p, value: %v
", &va1, va1, va1)
fmt.Printf("&va2: %v, pointer: %p, value: %v
", &va2, va2, va2)
This program prints:
&va1: 0x1030e0c0, pointer: 0x10328000, value: &{Hello Foo}
&va1: 0x1030e0c0, pointer: 0x10328050, value: &{TOO Boo}
&va2: 0x1030e0d0, pointer: 0x10328000, value: &{Hello Foo}
Note that the address of the variable va1 does not change, but what va1 points to does change. Also, the assignment of a pointer to va1 does not modify the value va1 pointed to.