在Go語言中,多態(tài)可以通過接口和類型斷言來實現(xiàn)。
定義一個接口,包含多個方法。
type Animal interface {
Sound() string
}
定義多個結(jié)構(gòu)體,并實現(xiàn)接口的方法。
type Dog struct{}
func (d Dog) Sound() string {
return "汪汪汪"
}
type Cat struct{}
func (c Cat) Sound() string {
return "喵喵喵"
}
使用多態(tài):
func main() {
animals := []Animal{Dog{}, Cat{}}
for _, animal := range animals {
fmt.Println(animal.Sound())
}
}
定義一個接口,可以為空接口interface{}
,表示任意類型。
type Animal interface {
Sound() string
}
定義多個結(jié)構(gòu)體,并實現(xiàn)接口的方法。
type Dog struct{}
func (d Dog) Sound() string {
return "汪汪汪"
}
type Cat struct{}
func (c Cat) Sound() string {
return "喵喵喵"
}
使用多態(tài):
func main() {
animals := []interface{}{Dog{}, Cat{}}
for _, animal := range animals {
if a, ok := animal.(Animal); ok {
fmt.Println(a.Sound())
}
}
}
以上兩種方法都可以實現(xiàn)多態(tài),具體使用哪種方法取決于實際需求和代碼設(shè)計。