Method expressions, conclusion

November 1, 2023

Today we’ll finish our discussoin of method expression from Monday and Tuesday.

Method expressions

Function values derived from methods are called with function call syntax; the receiver is provided as the first argument to the call. That is, given f := T.Mv, f is invoked as f(t, 7) not t.f(7).

We’ve already seen examples of this, the last two days. But to be honest, you’re unlikely to use these types of functions very frequently. What you will likely use a little bit more often is the topic for tomorrow: method values…

… To construct a function that binds the receiver, use a function literal or method value.

But one final note on method expressions:

It is legal to derive a function value from a method of an interface type. The resulting function takes an explicit receiver of that interface type.

For example, given:

type T struct {
	a int
}

func (tv T) Mv(a int) int { return 0 } // value receiver

type I interface {
	Mv(int) int
}

the expression I.Mv results in a function of the signature func(I, int) int.

Quotes from The Go Programming Language Specification Version of August 2, 2023


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .