Why does putting a value into a variable create a copy but de-referencing does not?
Is it a simple optimization of the compiler that knows that it can just use the address of the original structure, while creating a variable always allocates new memory?
Example 1:
x1 := &struct{ x int }{x: 0}
y1 := *x1
z1 := &y1
z1.x++
fmt.Printf("--- 1:
%#v
%#v
", x1, z1)
Example 2:
x2 := &struct{ x int }{x: 0}
z2 := &*x2
z2.x++
fmt.Printf("--- 2:
%#v
%#v
", x2, z2)
Run here: https://play.golang.org/p/myugNmjrQFj
Is there a a part of the go documentation that describes this behavior?
Is there a a part of the go documentation that describes this behavior?
Yes, the language spec. See https://golang.org/ref/spec