feat: struct embedding, enums
This commit is contained in:
40
go-by-example/structs/struct-embedding/struct-embedding.go
Normal file
40
go-by-example/structs/struct-embedding/struct-embedding.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type base struct {
|
||||
num int
|
||||
}
|
||||
|
||||
func (b base) describe() string {
|
||||
return fmt.Sprintf("base with num=%v", b.num)
|
||||
}
|
||||
|
||||
type container struct {
|
||||
base
|
||||
str string
|
||||
}
|
||||
|
||||
func main() {
|
||||
co := container{
|
||||
base: base{
|
||||
num: 1,
|
||||
},
|
||||
str: "Some name",
|
||||
}
|
||||
fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
|
||||
|
||||
fmt.Println("also num: ", co.base.num) // also num but can be without
|
||||
|
||||
// co can also use base method describe since it emebeds base
|
||||
fmt.Println("describe: ", co.describe())
|
||||
|
||||
var d describer = co
|
||||
fmt.Println("describer:", d.describe())
|
||||
}
|
||||
|
||||
type describer interface {
|
||||
describe() string
|
||||
}
|
||||
Reference in New Issue
Block a user