go by example part 3

This commit is contained in:
2022-01-05 22:56:08 +01:00
parent c1b7c64da2
commit c5983176c5
10 changed files with 337 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
// embedding of structs and interfaces to express a more seamless composition of types
package main
import "fmt"
type base struct {
num int
}
func (b base) describe() string {
return fmt.Sprintf("base with num=%v", b.num)
}
// container embeds a base
// embedding looks like a field without a name
type container struct {
base
str string
}
func main() {
// when creating structs with literals, initialize the embedding explicitly
co := container{
base: base{
num: 1,
},
str: "some name",
}
// access the bases fields directly
fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
// full path using the embedded type name
fmt.Println("also num:", co.base.num)
// container embeds base
// methods of base also become methods of a container
fmt.Println("describe:", co.describe())
type describer interface {
describe() string
}
// container implements describer interface because it embeds base
var d describer = co
fmt.Println("describer:", d.describe())
}