Table of Contents
When a Go struct embeds a type, you can often call that type’s methods directly on the outer value. For example, if employee embeds payroll, e.totalPay(30) can be shorthand for e.payroll.totalPay(30).

Call a method on an embedded type
package main
import "fmt"
type payroll struct {
dailyRate int
}
func (p payroll) totalPay(days int) int {
return p.dailyRate * days
}
type employee struct {
payroll
name string
}
func main() {
e := employee{payroll: payroll{dailyRate: 890}, name: "Sam"}
fmt.Println(e.totalPay(30)) // 26700
fmt.Println(e.payroll.totalPay(30)) // 26700
}The method still receives a payroll value. Embedding makes it selectable through employee.
Resolve a method name collision
If employee declares its own totalPay, e.totalPay selects that method. You can still call the embedded method explicitly with e.payroll.totalPay. If two embedded types provide a method with the same name at the same depth, qualify the selector with the intended embedded field.
Check receiver types before satisfying an interface
When a struct S embeds T, promoted methods with a T receiver are in the method sets of both S and *S. Promoted methods with a *T receiver are in the method set of *S. Embedding *T can make both receiver forms available in both method sets, provided the selector is unambiguous. Initialize an embedded pointer before calling a method that needs its value.
See the Go specification on embedded fields and the Go method set examples.
Reader Comments 0
Sign in with email or Google to join the discussion.