Go Struct Embedding
In Go, embedding is the way we achieve composition. It allows one struct to include another, giving it access to its fields and methods directly.
Basic example
Why use Embedding?
- Code Reuse: Instead of copying fields or methods, you can group them into a base struct and embed it.
- Polymorphism through Interfaces: If
baseimplements an interface,containerwill also implement it automatically because it "inherits" the methods.
Important Notes
- Shadowing: If both structs have a field with the same name, the outer struct's field "shadows" the inner one. You can still access the inner one using the full path (e.g.,
co.base.num). - Not Inheritance: Even though it looks like inheritance, Go uses composition. The
basestruct doesn't know about thecontainerstruct.