Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active February 7, 2024 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/5862dd87fedf8b6cac96c8307bbdb755 to your computer and use it in GitHub Desktop.
Save Integralist/5862dd87fedf8b6cac96c8307bbdb755 to your computer and use it in GitHub Desktop.
[Go copy struct from pointer] #go #golang
// structs are considered a primitive type and as such are passed by value.
// but if you have a pointer to struct you need to be careful not to assign it to a variable thinking you're getting a copy of the 'value'.
// you're only getting a copy of the 'pointer'! which means the newly assigned variable will mutate the underlying struct.
// so to make a copy you have to dereference the struct pointer first.
package main
import "fmt"
type Foo struct {
Bar string
Baz int
Qux bool
}
func main() {
f := &Foo{"BAR", 123, true}
fmt.Printf("f (%T): %#v\n", f, f)
f.Bar = "BAR!"
fmt.Printf("f (%T): %#v\n", f, f)
n := f // assigning f to n is assigning the pointer address to n
n.Bar = "BAR!!" // meaning we're still able to mutate the struct that f is pointing to
fmt.Printf("n (%T): %#v\n", n, n)
c := *f // here we deference the pointer to get the struct 'value' back, and assign the value not the pointer to `c`
c.Bar = "BAR!!!" // now this change only affects `c` and not the original struct that f and n point to
fmt.Printf("c (%T): %#v\n", c, c) // doesn't modify n or f
fmt.Printf("n (%T): %#v\n", n, n)
fmt.Printf("f (%T): %#v\n", f, f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment