有没有什么方法可以跨多个 struct 使用相同的函数来满足一个接口?
例如:
package main
import "fmt"
type Animal interface {
Speak() string
}
type Dog struct {}
func (d Dog) Speak() string {
return "Woof!"
}
type Wolf struct {}
func (w Wolf) Speak() string {
return "HOWWWWWWWWL"
}
type Beagle struct {}
func (b Beagle) Speak() string {
return "HOWWWWWWWWL"
}
type Cat struct {}
func (c Cat) Speak() string {
return "Meow"
}
func main() {
var a Animal
a = Wolf{}
fmt.Println(a.Speak())
}
因为Wolf和Beagle共享完全相同的函数,所以是否可以只编写一次该函数,然后在两个 struct 之间共享它,以便它们都能满足Animal呢?