« Back to Index

Go: copy struct from pointer

View original Gist on GitHub

Tags: #go

main.go

// 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)
}