跨多个结构重用函数以满足接口

时间:2015-08-13 20:23:28

标签: go

无论如何,您是否可以在多个结构中使用相同的函数来满足接口?

例如:

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?

1 个答案:

答案 0 :(得分:23)

您可以创建由“嚎叫”的每个动物嵌入的父结构。父结构实现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