0094-Go-结构体嵌入

环境

  • Time 2022-08-24
  • Go 1.19

前言

说明

参考:https://gobyexample.com/struct-embedding

目标

使用 Go 语言的结构体嵌入。

定义结构体

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)

    fmt.Println("describe:", co.describe())
}

实现接口

func main() {

    type describer interface {
        describe() string
    }

    var d describer = co
    fmt.Println("describer:", d.describe())
}

总结

使用 Go 语言的结构体嵌入。

附录

posted @ 2022-10-30 08:28  jiangbo4444  阅读(36)  评论(0)    收藏  举报