Here is a fundamental understanding that you lack: when a structure is passed to the function as a pointer, the function can change the original structure because it has a pointer to it. However, when the structure is passed to the function through its value, then in fact a NEW copy of the structure is created only for this function call, and any modifications to this new copy of the structure do not affect the original structure.
You can prove that this is how it works by printing out the actual addresses of the structures in question:
package main import "fmt" type T struct { Val string } func (t T) SetVal( s string ) { fmt.Printf("Address of copy is %p\n", &t); } func (t *T) SetVal2( s string ) { fmt.Printf("Pointer argument is %p\n", t); } func main() { v := T{"abc"} fmt.Printf("Address of v is %p\n", &v); v.SetVal("pdq") v.SetVal2("xyz") }
The above code leads to the conclusion when I run it on the Go playground:
Address of v is 0xf840001290 Address of copy is 0xf8400013e0 Pointer argument is 0xf840001290
Notice how the first and third pointers are printed, which means they have the same structure. But the second pointer is different because it is a copy.
By the way, this is similar to how the C structure / function parameters work.
source share