dongtuo5611 2018-05-02 21:33
浏览 33
已采纳

将函数分配给返回接口值的函数类型,

Im trying to define a couple of interface to refactor some code and I'm getting a problem where Go is not letting me assign functions to variables. This is the set up

main.go

    type Gettable interface {
        Get() int64
    }

    type MyFunction func(int64) (Gettable, error)

    func main() {

        var f MyFunction
        f = sub.TestFn2
        a, _ := f(1)
        fmt.Println(a)
    }

main/sub

package sub

type MyStruct struct {
    Val int64
}

func (v MyStruct) Get() int64 {
    return v.Val
}

func TestFn2(a int64) (MyStruct, error) {
    return MyStruct{a}, nil
}

I'm trying to define a generic function type, and in the sub package create the concrete functions

and ideally i want to store the functions in a map and call them with something like

FnMap["fnName"]()

I'm not there yet,

im getting an error saying

/topics.go:27:4: cannot use sub.TestFn2 (type func(int64) (sub.MyStruct, error)) as type MyFunction in assignment

but MyStruct clearly implements the interface Gettable

  • 写回答

2条回答 默认 最新

  • dongyu4863 2018-05-02 21:48
    关注

    This error occurs because of signature don't match. You code shared is:

    //shared code
    //---------------------------------------------
    type Gettable interface {
        Get() int64
    }
    type MyFunction func(int64) (Gettable, error)
    

    So you need replace MyStruct by Gettable.

    //main/sub
    //---------------------------------------------
    type MyStruct struct {
        Val int64
    }
    
    func (v MyStruct) Get() int64 {
        return v.Val
    }
    
    //this signature of TestFn2 is different of MyStruct
    //-[TestFn2] func (a int64) (MyStruct, error)
    //-[MyFunction] func(int64) (Gettable, error)
    func TestFn2(a int64) (Gettable, error) {//<-- replace by Gettable here
        return MyStruct{a}, nil
    }
    

    Running your code:

    //main.go
    //---------------------------------------------
    
    func main() {
            var f MyFunction
            f = TestFn2
            a, _ := f(1)
            fmt.Println(a)
    }   
    

    Result is:

    {1}
    

    See in playground: https://play.golang.org/p/sRsXix8E_83

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害