英文:
Reuse a function across multiple structs to satisfy an interface
问题
有没有办法在多个结构体之间使用相同的函数来满足接口?
例如:
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 接口?
英文:
Is there anyway that you can use the same function across multiple structs to satisfy an interface?
For example:
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())
}
Because Wolf and Beagle share the exact same function, is there anyway to write that function once, then share it between the two structs so that they both satisfy Animal?
答案1
得分: 37
你可以创建一个父结构体,该结构体被每个“嚎叫”的动物嵌入。父结构体实现了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())
}
你可以在这里查看代码:https://play.golang.org/p/IMFnWdeweD
英文:
You can create a parent struct that is embedded by each of the animals that "howl". The parent struct implements the Speak() string
method, which means Wolf
and Beagle
implement the Animal
interface.
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())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论