Determine method sets
Determine method sets
A method set is the collection of methods belonging to a type. For a defined non-pointer, non-interface type T without embedding, T has methods with receiver T; *T has methods with receiver T or *T. Automatic addressing does not change these sets.
package main
import ( "fmt")
type Counter int
func (c Counter) Value() int { return int(c) }func (c *Counter) Inc() { (*c)++ }func main() { var c Counter = 2 c.Inc() fmt.Println(Counter.Value(c), (*Counter).Value(&c)) (*Counter).Inc(&c) fmt.Println(c)}Counter.Value and (*Counter).Value are valid method expressions. Counter.Inc is not: c.Inc() works because the variable is addressable, not because Counter gained another method.
Expected output:
3 34Compare embedding a value and a pointer
package main
import ( "fmt")
type Base int
func (b Base) Value() int { return int(b) }func (b *Base) Inc() { (*b)++ }
type A struct{ Base }type B struct{ *Base }
func main() { a := A{Base: 2} n := Base(5) b := B{Base: &n} (*A).Inc(&a) B.Inc(b) fmt.Println(A.Value(a), B.Value(b))}Embedding Base promotes its value methods to A and *A, and pointer methods to *A. Embedding *Base promotes both kinds to B and *B, absent conflicts. B must contain a usable pointer before a method dereferences it. These rules also determine interface satisfaction, covered next chapter.
Expected output:
3 6Try it locally
Define Meter int with value Read() int and pointer Add(n int). Use method expressions to increase 4 by 3 and print it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Methods 05: Determine method sets
Check the lesson objective before moving on.
Which methods are in the method set of *T for a simple defined T?
What does embedding *Base promote to B, absent conflicts?