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 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题