Resolve embedded method conflicts
Resolve embedded method conflicts
Embedding makes methods available through an outer struct. A selector chooses a unique member at the shallowest embedding depth. Two members with the same name at that depth make the selector ambiguous. Qualify the embedded field or declare an explicit outer method.
package main
import ( "fmt")
type Screen struct{}
func (Screen) Name() string { return "screen" }
type Printer struct{}
func (Printer) Name() string { return "printer" }
type Device struct { Screen Printer}
func main() { d := Device{} fmt.Println(d.Screen.Name(), d.Printer.Name())}d.Name() is ambiguous. d.Screen.Name() and d.Printer.Name() explicitly choose the receiver. Embedding order does not resolve the conflict.
Expected output:
screen printerDefine explicit outer behavior
package main
import ( "fmt")
type A struct{}
func (A) Label() string { return "A" }
type B struct{}
func (B) Label() string { return "B" }
type Both struct { A B}
func (b Both) Label() string { return b.A.Label() + "+" + b.B.Label() }func main() { b := Both{} fmt.Println(b.Label(), b.A.Label())}The outer Label is at depth zero and takes precedence. It delegates to both fields. This is composition, not inheritance or virtual method overriding; the embedded values retain their own methods.
Expected output:
A+B ATry it locally
Define Left and Right with Side() returning L and R. Embed both into Pair and implement Pair.Side() returning L/R by explicit delegation. Print the result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Methods 06: Resolve embedded method conflicts
Check the lesson objective before moving on.
What happens when two embedded methods share a name at the shallowest depth?
How can an outer type provide its own unambiguous behavior?