douban5644 2016-10-08 18:50
浏览 70
已采纳

带回调映射到具有接收器的函数的语法

is it possible to create in golang a map containing functions which have a receiver?

I want to accomplish the following

Function Callbacks:

func (my *mystruct) doSometing(int parameter1){
// do something
}

func (my *mystruct) doAnotherThing(int parameter1){
// do something
}

Map containing a pointer to the function

var lookupMap = map[string]func(int){
    "action1" : doSomething,
    "action2" : doAnotherThing
}

This unfortunately doesn't work because the callback functions are bound to a receiver. Go compiler says:

"undefined doSomething"

My Question:

What is the syntax to create a map where the values are functions which are bound to a specific receiver?

Something like (pseudo code):

var lookupMap = map[string]((*mystruct)func(int)){
}

Any help appreciated!

  • 写回答

2条回答 默认 最新

  • duanhu7400 2016-10-08 18:58
    关注

    With Method Values

    You may use Method values for this purpose. A method value is a function value with implicit receiver. Quoting from Spec: Method values:

    If the expression x has static type T and M is in the method set of type T, x.M is called a method value.

    So the syntax for a method value is x.M, where for example x is a value of the type, M is the name of the method. This results in a function with the same parameters (and return types) as the method without a receiver, as the receiver will be saved with the method value and will be implicit.

    So this means to store method values for your doSometing() and doAnotherThing() methods, the function type will simply be func (int) (no receiver).

    Here's a working example:

    type mystruct struct {
        name string
    }
    
    func (my *mystruct) doA(i int) {
        fmt.Printf("[doA]: I'm %s, param is: %d
    ", my.name, i)
    }
    
    func (my *mystruct) doB(i int) {
        fmt.Printf("[doB]: I'm %s, param is: %d
    ", my.name, i)
    }
    
    func main() {
        my1 := &mystruct{"Bob"}
        my2 := &mystruct{"Alice"}
        lookupMap := map[string]func(int){
            "action1": my1.doA,
            "action2": my2.doB,
        }
    
        lookupMap["action1"](11)
        lookupMap["action2"](22)
    }
    

    Output (try it on the Go Playground):

    [doA]: I'm Bob, param is: 11
    [doB]: I'm Alice, param is: 22
    

    With Method Expressions

    If you don't want the receiver saved in the dictionary (within the method values), you can go along with the Method expressions.

    The difference is that when you obtain a function value, you don't use x.M but T.M, which will result in a function value, with a function type having the same parameters (and return types), but the receiver type will also be in the parameter list, and in the first place. See quote from Spec: Method expressions:

    If M is in the method set of type T, T.M is a function that is callable as a regular function with the same arguments as M prefixed by an additional argument that is the receiver of the method.

    So the function type to work with will look like this in your case: func(*mystruct, int)

    Also, since the receiver will not be saved, you have to provide it when calling these functions.

    See this working example (which is the modification of the first example):

    type mystruct struct {
        name string
    }
    
    func (my *mystruct) doA(i int) {
        fmt.Printf("[doA]: I'm %s, param is: %d
    ", my.name, i)
    }
    
    func (my *mystruct) doB(i int) {
        fmt.Printf("[doB]: I'm %s, param is: %d
    ", my.name, i)
    }
    
    func main() {
        lookupMap := map[string]func(*mystruct, int){
            "action1": (*mystruct).doA,
            "action2": (*mystruct).doB,
        }
    
        my1 := &mystruct{"Bob"}
        my2 := &mystruct{"Alice"}
        lookupMap["action1"](my1, 11)
        lookupMap["action2"](my2, 22)
    }
    

    Output is the same (try it on the Go Playground):

    [doA]: I'm Bob, param is: 11
    [doB]: I'm Alice, param is: 22
    

    See similar questions:

    golang - pass method to function

    golang function alias on method receiver

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

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line