Files
bulma/interface_named.go
T

37 lines
534 B
Go

package main
import "fmt"
// 定义接口(可发声的物体)
type Sounder interface {
MakeSound() string
}
// 狗实现Sounder接口
type Dog struct{}
func (d Dog) MakeSound() string {
return "汪汪"
}
// 猫实现Sounder接口
type Cat struct{}
func (c Cat) MakeSound() string {
return "喵喵"
}
// 多态:接收Sounder接口,调用不同实现
func animalSound(s Sounder) {
fmt.Println(s.MakeSound())
}
func main() {
var s Sounder
s = Dog{}
animalSound(s) // 汪汪
s = Cat{}
animalSound(s) // 喵喵
}