Golang中的函数映射(map)带有接收器。

huangapple go评论98阅读模式
英文:

Golang a map of functions with a receiver

问题

有没有办法创建一个函数指针的映射,但是这些函数需要接收者?我知道如何在普通函数中实现这个:

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

但是对于需要接收者的函数,你能这样做吗?类似于这样(尽管我尝试过,但它不起作用):

package main

type someStruct struct {
    x int
}

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

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

一个明显的解决方法是将结构体作为参数传递,但这比我想要的要麻烦一些。

英文:

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

得分: 7

你可以使用方法表达式来实现这个:

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

调用方式有些不同,因为方法表达式将接收者作为第一个参数。

这是你的示例修改后的代码:

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

这是一个供你测试的 Go playground:

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

英文:

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

huangapple
  • 本文由 发表于 2017年8月3日 08:06:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/45472816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定