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条)

报告相同问题?

悬赏问题

  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题