doutu7123 2016-08-23 07:47
浏览 9
已采纳

有没有一种方法可以通用地表示一组相似的功能?

package main

import "fmt"

type Pet interface {
    Bark()
}

type Dog int

func (d Dog) Bark() {
    fmt.Println("W! W! W!")
}

type Cat int

func (c Cat) Bark() {
    fmt.Println("M! M! M!")
}

type AdoptFunc func(pet Pet)

func adoptDog(dog Dog) {
    fmt.Println("You live in my house from now on!")
}
func adoptCat(cat Cat) {
    fmt.Println("You live in my house from now on!")
}

func main() {
    var adoptFuncs map[string]AdoptFunc
    adoptFuncs["dog"] = adoptDog // cannot use adoptDog (type func(Dog)) as type AdoptFunc in assignment
    adoptFuncs["cat"] = adoptCat // the same as above
}

As the code above, is there a way to use a map or array to collect a bunch of similar functions adoptXxx? If not, what is right pattern to use for this situation?

  • 写回答

1条回答 默认 最新

  • douxian6008 2016-08-23 07:53
    关注

    To use the map as a function collection you'll have to change the signature of your functions to match. func(Pet) is not the same type as func(Dog).

    You can re-write AdoptXXX functions to take in Pet and do a type select to ensure correct pet is being input:

    func adoptDog(pet Pet) {
        if _, ok := pet.(Dog); !ok {
            // process incorrect pet type
        }
        fmt.Println("You live in my house from now on!")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作