Prior Knowledge
- Pointer and Value Receiver
package main
type V struct{}
func (*V) method() {}
func main() {
var v V
v.method() // This is also correct.
p := &v
p.method() // No problem.
}
Methods with pointer receivers can take either a value or a pointer as the receiver.
Methods and pointer indirection
package main
type V struct{}
func (V) method() {}
func main() {
var v V
v.method() // No problem.
p := &v
p.method() // This is also correct.
}
Methods with value receivers can take either a value or a pointer as the receiver.
Methods and pointer indirection (2)
Notes: Don’t be confused with “Which one implements the interface? Pointer or Value receiver?”. They are totally different things.
- Structs and embedding (from golang specification)
Given a struct type S and a defined type T, promoted methods are included in the method set of the struct as follows:
- If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.
- If S contains an embedded field *T, the method sets of S and *S both include promoted methods with receiver T or *T.
Code Example
Exercise (experiment):
package main
import (
"fmt"
)
type base struct{}
func (*base) hello() {
fmt.Println("hello from base")
}
type derived struct {
base
}
func (derived) hello() {
fmt.Println("hello from derived")
}
func main() {
b := base{}
b.hello()
d := &derived{}
d.hello()
}