go

Does go auto-bind funcs to struct?


Say I have this:

type Handler struct{}

func helper(f func()){
   f() // calls h.Mount() or just Mount() w/o reference to h?
}

func (h Handler) Mount() {}

func init(){
  h:=Handler{}
  helper(h.Mount)
}

When the helper func receives h.Mount (a func), can it call it directly, or does it need a reference to the handler h, to call it properly? This compiles and runs as-is, so I don't know.


Solution

  • Yes. The Go book refers to this as a method value.

    Usually we we select and call a method in the same expression, as in p.Distance(), but it's possible to separate these two operations. The selector p.Distance yields a method value, a function that binds a method (Point.Distance) to a specific receiver value p. This function can then be invoked without a receiver value; it needs only the non-receiver arguments.

    (Source: The Go Programming Language, Donovan and Kernighan, page 164.)