douyun6399 2017-08-03 00:06
浏览 36
已采纳

Golang与接收器的功能图

Is there anyway to make a map of function pointers, but functions that take recievers? I know how to do it with regular functions:

package main

func someFunc(x int) int {
    return x
}

func main() {
    m := make(map[string]func(int)int, 0)
    m["1"] = someFunc
    print(m["1"](56))
}

But can you do that with functions that take recievers? Something like this (though I've tried this and it doesn't work):

package main

type someStruct struct {
    x int
}

func (s someStruct) someFunc() int {
    return s.x
}

func main() {
    m := make(map[string](someStruct)func()int, 0)
    s := someStruct{56}
    m["1"] = someFunc
    print(s.m["1"]())
}

An obvious work around is to just pass the struct as a parameter, but that's a little dirtier than I would have liked

  • 写回答

1条回答 默认 最新

  • dtziv24262 2017-08-03 02:16
    关注

    You can do that using Method Expressions:

    https://golang.org/ref/spec#Method_expressions

    The call is a bit different, since the method expression takes the receiver as the first argument.

    Here's your example modified:

    package main
    
    type someStruct struct {
        x int
    }
    
    func (s someStruct) someFunc() int {
        return s.x
    }
    
    func main() {
        m := make(map[string]func(someStruct)int, 0)
        s := someStruct{56}
        m["1"] = (someStruct).someFunc
        print(m["1"](s))
    }
    

    And here's a Go playground for you to test it:

    https://play.golang.org/p/PLi5A9of-U

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教