Composition Instead of Inheritance
In Go, you can "extend" functionality by embedding structs. When a struct embeds another struct, it inherits its methods and fields.
Example of Composition (Struct Embedding):
Output:
Composition Instead of Inheritance
In Go, you can "extend" functionality by embedding structs. When a struct embeds another struct, it inherits its methods and fields.
Example of Composition (Struct Embedding):
package main
===========================
import "fmt"
// Base struct
type Base struct {
ID int
}
// Method of Base struct
func (b *Base) PrintID() {
fmt.Printf("ID: %d\n", b.ID)
}
===========================
// Extended struct using composition
type Extended struct {
Base // Embedding Base struct
Name string
}
===========================
func main() {
// Initialize Extended
ext := Extended{
Base: Base{ID: 42},
Name: "Le Giang",
}
// Access methods from Base
ext.PrintID()
// Access field from Extended
fmt.Println("Name:", ext.Name)
}
Output:
ID: 42 Name: Le GiangThank
No comments:
Post a Comment