無論如何,您可以在多個結構中使用相同的函數來滿足接口嗎?例如:package mainimport "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 共享完全相同的函數,所以是否可以編寫一次該函數,然后在兩個結構之間共享它,以便它們都滿足 Animal?
- 1 回答
- 0 關注
- 156 瀏覽
添加回答
舉報
0/150
提交
取消