A quick reminder: In today’s live stream, I’ll be deploying a Go app to Kubernetes! I hope you’ll join me!
Today we continue the explanation of Method values. There’s nothing too surprising today. The spec mostly just confirms what should seem natural…
Method values
…
As in the discussion of method expressions above, consider a struct type
T
with two methods,Mv
, whose receiver is of typeT
, andMp
, whose receiver is of type*T
.type T struct { a int } func (tv T) Mv(a int) int { return 0 } // value receiver func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver var t T var pt *T func makeT() T
The expression
t.Mv
yields a function value of type
func(int) int
These two invocations are equivalent:
t.Mv(7) f := t.Mv; f(7)
Similarly, the expression
pt.Mp
yields a function value of type
func(float32) float32
Again, nothing super surprising here. The main contrast with method expressions is that the receiver type is not reflected in the final function value type. That is to say, regardless of whether the method has a pointer or value receiver, the function value has the same type. In fact, regardless of the receiver’s base type, the function value is the same, given the same method signature:
type Person struct {
/* ... */
}
func (p Person) Greet(name string) {}
func (p *Person) SayHi(name string) {}
type Dog string
func (d Dog) Speak(sound string) {}
var (
p Person
d Dog
x = p.Greet // x, y, and z all
y = p.SayHi // have the same type:
z = d.Speak // func(string)
)
Quotes from The Go Programming Language Specification Version of August 2, 2023