为了账号安全,请及时绑定邮箱和手机立即绑定

不能使用(类型函数(d 狗))作为类型函数(动物动物)

不能使用(类型函数(d 狗))作为类型函数(动物动物)

Go
宝慕林4294392 2022-10-04 19:54:15
我正在努力编写一个方法可以同时将和方法作为其参数,而我的IDE告诉我:callGetNamegetCatNamegetDogName不能使用“获取狗名”(类型函数(d 狗))作为类型函数(动物动物)package maintype Animal struct {    Name string}type Cat struct {    Animal}type Dog struct {    Animal}func getCatById(c Cat) {}func validateDogNames(d Dog) {}func invokeFunc(f func(animal Animal)) {}func main() {    invokeFunc(getCatById)    invokeFunc(validateDogNames)}我试图分析原因,也许是因为高浪支持多重继承?请让我知道我是否在做一些愚蠢的事情,或者有没有更好的方法来实现这一目标?========关于我为什么要尝试这个:在go-kit框架中,我必须为每个定义的服务方法编写makeEndpoint函数。我用反射来采用一个通用的制作端点,如下所示:func NewProductEndpoints() ProductEndpoints {    ps := service.NewProductService()    return ProductEndpoints{        GetProductById: makeEndpoint(ps, util.GetFunctionName(ps.GetProductById)),        CreateProduct: makeEndpoint(ps, util.GetFunctionName(ps.CreateProduct)),    }}func makeEndpoint(s service.ProductService, funcName string) kitEndpoint.Endpoint {    return func(ctx context.Context, request interface{}) (response interface{}, err error) {        req := request.(domain.ProductDTO)        currFunc := reflect.ValueOf(s).MethodByName(funcName)        args := []reflect.Value{reflect.ValueOf(req)}        res := currFunc.Call(args)[0]        return res, nil    }}想知道是否有更好的方法来实现。提前致谢。
查看完整描述

1 回答

?
喵喔喔

TA贡献1735条经验 获得超5个赞

所以你以一种相当OOP的方式思考,Go没有继承(澄清它有结构嵌入,这就是你在第一个例子中所做的)。我们倾向于用组合来解决问题。


您可以考虑解决问题的一种方法是如下所示。


package main


import (

    "fmt"

)


type Namer interface {

    Name() string

}


type Cat struct {

    name string

}


func (c Cat) Name() string {

    return c.name

}


type Dog struct {

    name string

}


func (d Dog) Name() string {

    return d.name

}


func PetName(n Namer) {

    fmt.Println(n.Name())

}


func main() {

    PetName(Dog{name: "Fido"})

    PetName(Cat{name: "Mittens"})

}

名称可以改进,但它应作为可以采取的方法的基本示例。


编辑:基于下面留下的评论的示例


package main


import (

    "fmt"

)


type Invoker interface {

    Invoke()

}


type Dog struct{}


func (Dog) Bark() {

    fmt.Println("Woof")

}

func (d Dog) Invoke() {

    d.Bark()

}


type Cat struct{}


func (Cat) Meow() {

    fmt.Println("Meow")

}

func (c Cat) Invoke() {

    c.Meow()

}


func CallFunc(i Invoker) {

    i.Invoke()

}


func main() {

    CallFunc(Cat{})

    CallFunc(Dog{})

}


查看完整回答
反对 回复 2022-10-04
  • 1 回答
  • 0 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号