1

I recently learned that you can invoke a receiver's method by doing (*receiverType).method(receiver), where the first parameter is always the receiver itself.

func main() {
    c := &Cool{}
    c.say("Cool!")
    (*Cool).say(c, "Hot!") // <-- this
}

type Cool struct {
}

func (it *Cool) say(s string) {
    fmt.Println(s)
}

https://play.golang.org/p/vVjr42ceqA

Is there a name for this kind of syntax? Why does this compile?

Some Noob Student
  • 14,186
  • 13
  • 65
  • 103
  • 4
    These are normal method expressions as described in the language spec here https://golang.org/ref/spec#Method_expressions. Rule of thumb: Look it up in the spec first. – Volker Feb 28 '17 at 09:27
  • 2
    See more on this here: [golang - pass method to function](http://stackoverflow.com/questions/38897529/golang-pass-method-to-function/38897667#38897667); and [golang function alias on method receiver](http://stackoverflow.com/questions/28251283/golang-function-alias-on-method-receiver/28252088#28252088). – icza Feb 28 '17 at 09:29
  • Thanks for the tips and the links! You guys are awesome. – Some Noob Student Feb 28 '17 at 18:50

0 Answers0