douceng7070 2015-08-13 20:23
浏览 16
已采纳

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

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条回答 默认 最新

  • duanbamo0127 2015-08-13 20:27
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?