在多个结构体之间重用一个函数以满足接口的要求。

huangapple go评论85阅读模式
英文:

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方法,这意味着WolfBeagle实现了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())
}

https://play.golang.org/p/IMFnWdeweD

huangapple
  • 本文由 发表于 2015年8月14日 04:23:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/31997753.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定