Method sets
Method sets¶
The method set of a type determines the methods that can be called on an operand of that type. Every type has a (possibly empty) method set associated with it:
- The method set of a defined type
Tconsists of all methods declared with receiver typeT. - The method set of a pointer to a defined type
T(whereTis neither a pointer nor an interface) is the set of all methods declared with receiver*TorT. - The method set of an interface type is the intersection of the method sets of each type in the interface's type set (the resulting method set is usually just the set of declared methods in the interface).
Further rules apply to structs (and pointer to structs) containing embedded fields, as described in the section on struct types. Any other type has an empty method set.
In a method set, each method must have a unique non-blank method name.
The Spec¶
There are two important clauses in the Go Language Specification about method sets. They are as follows:
Method Sets: A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other named type T consists of all methods with receiver type T. The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T). Any other type has an empty method set. In a method set, each method must have a unique name.
Calls: A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x’s method set contains m, x.m() is shorthand for (&x).m().