Interfaces & CompositionAdvanced
1Question 1 of 1
goHow does Struct Embedding provide composition over inheritance in Go?
Explanation & Concept
Go favors composition through **Struct Embedding**: fields and methods of an embedded struct are 'promoted' to the outer struct, allowing direct access as if they were declared natively.
Code Example
go
package main
import "fmt"
type Author struct {
Name string
}
func (a Author) Sign() string {
return "Written by " + a.Name
}
type Article struct {
Author // Embedded struct
Title string
}
func main() {
post := Article{
Author: Author{Name: "Robin"},
Title: "Go Architecture Patterns",
}
// Sign() method is promoted directly to post!
fmt.Println(post.Sign()) // "Written by Robin"
}How It Works & Key Takeaways
Composition via embedding achieves code reuse without the rigid fragility of deep inheritance hierarchies.
Mock Test · 1 Questions · Optional
Ready for Select Statement?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions