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

我正在努力编写一个方法可以同时将和方法作为其参数,而我的IDE告诉我:callGetNamegetCatNamegetDogName


不能使用“获取狗名”(类型函数(d 狗))作为类型函数(动物动物)


package main


type 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

    }

}

想知道是否有更好的方法来实现。提前致谢。


宝慕林4294392
浏览 116回答 1
1回答

喵喔喔

所以你以一种相当OOP的方式思考,Go没有继承(澄清它有结构嵌入,这就是你在第一个例子中所做的)。我们倾向于用组合来解决问题。您可以考虑解决问题的一种方法是如下所示。package mainimport (    "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 mainimport (    "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{})}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go