Struct Embedding
package main
import "fmt"
// Define a struct named 'base' with a field 'num'
type base struct {
num int
}
// Method 'describe' for the 'base' struct, returns a string describing the base struct
func (b base) describe() string {
return fmt.Sprintf("base with num=%v", b.num)
}
// Define a struct named 'container' that embeds the 'base' struct and has an additional field 'str'
type container struct {
base // Embedding the 'base' struct
str string
}
func main() {
// Create an instance of the 'container' struct with field values
co := container{
base: base{
num: 1,
},
str: "some name",
}
// Print the values of the 'container' struct fields
fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
// Access the 'num' field of the embedded 'base' struct directly
fmt.Println("also num:", co.base.num)
// Call the 'describe' method on the 'container' struct, which internally calls the 'describe' method of the embedded 'base' struct
fmt.Println("describe:", co.describe())
// Define an interface named 'describer' with a 'describe' method
type describer interface {
describe() string
}
// Create a variable 'd' of type 'describer' and assign the 'container' struct to it
var d describer = co
// Call the 'describe' method on the 'describer' interface, which calls the overridden method in the 'container' struct
fmt.Println("describer:", d.describe())
}Output
Last updated