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 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角