Golang的接口是实现多态的关键。通过定义合适的接口,您可以编写通用的代码逻辑,以适应不同的具体实现。这样可以提高代码的灵活性和可扩展性。以下是一个示例:
goCopy codetype Animal interface {
Sound() string
}
type Dog struct{}
func (d Dog) Sound() string {
return "Woof!"
}
type Cat struct{}
func (c Cat) Sound() string {
return "Meow!"
}
func MakeSound(a Animal) {
fmt.Println(a.Sound())
}
func main() {
dog := Dog{}
cat := Cat{}
MakeSound(dog) // 输出 "Woof!"
MakeSound(cat) // 输出 "Meow!"
}