Second rule of Selectors

October 24, 2023


  1. For a value x of type I where I is an interface type, x.f denotes the actual method with name f of the dynamic value of x. If there is no method with name f in the method set of I, the selector expression is illegal.
type I interface {

type Person struct {
  Name string

func (p *Person) Greet() {
  fmt.Printf("Hello, %s", p.Name)

var I x
x = &Person{}

x.Greet // denotes the actual Greet method Person, which is the dynamic value of x

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 .

Related Content

Method expressions, conclusion

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.

Illegal selectors

We’ll cover the last 3 rules of selectors in one go today, since they’re all about illegal selectors. Selectors … In all other cases, x.f is illegal. Simple enough. The cases mentioned in rules 1-3 ar ethe only valid uses of x.f. All others are illegal. var x int x.chicken // illegal! If x is of pointer type and has the value nil and x.f denotes a struct field, assigning to or evaluating x.

Type parameters in method definitions

Yesterday we saw that when a method is defined on a generic type, the receiver must include type parameters. Now for all the relevant details: Method declarations … … Syntactically, this type parameter declaration looks like an instantiation of the receiver base type: the type arguments must be identifiers denoting the type parameters being declared, one for each type parameter of the receiver base type. The type parameter names do not need to match their corresponding parameter names in the receiver base type definition, and all non-blank parameter names must be unique in the receiver parameter section and the method signature.