Golang / GoLang Interfaces and Object Oriented Interview Questions
How does embedding propagate interface satisfaction through multiple levels?
Embedding is transitive. If type C embeds type B which embeds type A, then C's method set includes all methods from A and B. This means C can satisfy interfaces that A satisfies — through a chain of embeddings.
type Named interface { Name() string } type Described interface { Describe() string } type NamedAndDescribed interface { Named; Described } // Level 1 type Animal struct{ name string } func (a Animal) Name() string { return a.name } // Level 2 â embeds Animal type Pet struct { Animal Owner string } func (p Pet) Describe() string { return fmt.Sprintf("%s owned by %s", p.Name(), p.Owner) } // Level 3 â embeds Pet type ServiceAnimal struct { Pet BadgeID string } // ServiceAnimal inherits Name() from Animal (via Pet) and // Describe() from Pet sa := ServiceAnimal{ Pet: Pet{ Animal: Animal{name: "Rex"}, Owner: "Alice", }, BadgeID: "K9-042", } var nd NamedAndDescribed = sa // ServiceAnimal satisfies NamedAndDescribed fmt.Println(nd.Name()) // Rex fmt.Println(nd.Describe()) // Rex owned by Alice // Method ambiguity: what if both A and B define the same method? type X struct { Val int }; func (x X) Tag() string { return "X" } type Y struct { Val int }; func (y Y) Tag() string { return "Y" } type Ambiguous struct { X; Y } // a := Ambiguous{}; a.Tag() // COMPILE ERROR: ambiguous selector a.Tag // Must qualify: a.X.Tag() or a.Y.Tag()
Disambiguation rule: if two embedded types provide a method with the same name at the same depth, accessing that method on the outer struct is a compile error. The solution is to define the method explicitly on the outer type, which takes precedence and resolves the ambiguity.
More Related questions...