blog icon indicating copy to clipboard operation
blog copied to clipboard

confusion could be elaborated on

Open tommyjcarpenter opened this issue 5 years ago • 1 comments

I found your post here: https://nathanleclaire.com/blog/2014/08/09/dont-get-bitten-by-pointer-vs-non-pointer-method-receivers-in-golang/

after reading this page: https://gobyexample.com/methods

my question is: why does go not seem to care that you pass the correct type (pointer or not) into a method? Specifically, at the end you have a code block:

func main() {
    m := &Mutatable{0, 0} // line * below seems to work even without the & here
    fmt.Println(m)
    m.StayTheSame()
    fmt.Println(m)
    m.Mutate() . //*
    fmt.Println(m)
}

however, if you just did m := Mutatable{0, 0}, then m.Mutate() still works. Why? What is the effect of this? Why doesn't the compiler complain about m not being a pointer?

tommyjcarpenter avatar Jan 30 '20 19:01 tommyjcarpenter

If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m():

https://golang.org/ref/spec#Calls

shunkica avatar Apr 26 '21 20:04 shunkica