Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Golang]struct pointer
#https://play.golang.org/p/bGs5TPZksJ
#http://nathanleclaire.com/blog/2014/08/09/dont-get-bitten-by-pointer-vs-non-pointer-method-receivers-in-golang/
import "fmt"
type foo struct {
name string
}
type bar struct {
f *foo
name string
}
func (b bar) changeNames() {
b.name = "changed"
b.f.name = "changed"
}
type baz struct {
f foo
name string
}
func (b baz) changeNames() {
b.name = "changed"
b.f.name = "changed"
}
func main() {
b := bar{name: "bar", f: &foo{name: "foo"}}
fmt.Println(b.name, b.f.name)
b.changeNames()
fmt.Println(b.name, b.f.name)
bz := baz{name: "baz", f: foo{name: "foo2"}}
fmt.Println(bz.name, bz.f.name)
bz.changeNames()
fmt.Println(bz.name, bz.f.name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment