溫馨提示×

golang多態怎么實現

小億
105
2023-11-01 23:10:15
欄目: 編程語言

在Go語言中,多態可以通過接口和類型斷言來實現。

  1. 使用接口實現多態:

定義一個接口,包含多個方法。

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())
    }
}
  1. 使用類型斷言實現多態:

定義一個接口,可以為空接口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())
        }
    }
}

以上兩種方法都可以實現多態,具體使用哪種方法取決于實際需求和代碼設計。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女