利用接口实现多态

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!"
}

你可能感兴趣的:(GO语言,GOLang,技巧,go,开发语言,青少年编程)