golang多态怎么实现

   2025-02-15 3310
核心提示:在Go语言中,多态可以通过接口和类型断言来实现。使用接口实现多态:定义一个接口,包含多个方法。type Animal interface {Sound

在Go语言中,多态可以通过接口和类型断言来实现。

使用接口实现多态:

定义一个接口,包含多个方法。

type Animal interface {    Sound() string}

定义多个结构体,并实现接口的方法。

type Dog struct{}func (d Dog) Sound() string {    return "汪汪汪"}type Cat struct{}func (c Cat) Sound() string {    return "喵喵喵"}

使用多态:

func main() {    animals := []Animal{Dog{}, Cat{}}    for _, animal := range animals {        fmt.Println(animal.Sound())    }}
使用类型断言实现多态:

定义一个接口,可以为空接口interface{},表示任意类型。

type Animal interface {    Sound() string}

定义多个结构体,并实现接口的方法。

type Dog struct{}func (d Dog) Sound() string {    return "汪汪汪"}type Cat struct{}func (c Cat) Sound() string {    return "喵喵喵"}

使用多态:

func main() {    animals := []interface{}{Dog{}, Cat{}}    for _, animal := range animals {        if a, ok := animal.(Animal); ok {            fmt.Println(a.Sound())        }    }}

以上两种方法都可以实现多态,具体使用哪种方法取决于实际需求和代码设计。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言