无论如何,您是否可以在多个结构中使用相同的函数来满足接口?
例如:
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共享完全相同的功能,无论如何都要编写一次该函数,然后在两个结构之间共享它们以便它们都满足Animal?
答案 0 :(得分:23)
您可以创建由“嚎叫”的每个动物嵌入的父结构。父结构实现Speak() string
方法,这意味着Wolf
和Beagle
实现Animal
接口。
package main
import "fmt"
type Animal interface {
Speak() string
}
type Howlers struct {
}
func (h Howlers) Speak() string {
return "HOWWWWWWWWL"
}
type Dog struct {}
func (d Dog) Speak() string {
return "Woof!"
}
type Wolf struct {
Howlers
}
type Beagle struct {
Howlers
}
type Cat struct {}
func (c Cat) Speak() string {
return "Meow"
}
func main() {
var a Animal
a = Wolf{}
fmt.Println(a.Speak())
}