Kok*_*zzu 8 key function map go
如何使用函数作为地图的关键?例如:
type Action func(int)
func test(a int) { }
func test2(a int) { }
func main() {
x := map[Action]bool{}
x[test] = true
x[test2] = false
}
Run Code Online (Sandbox Code Playgroud)
这些代码会显示错误: invalid map key type Action
小智 6
虽然函数不能是键,但函数指针可以。
package main
import "fmt"
type strFunc *func() string
func main() {
myFunc := func() string { return "bar" }
m := make(map[strFunc]string)
m[(strFunc)(&myFunc)] = "f"
for f, name := range m {
fmt.Println((*f)(), name)
}
}
Run Code Online (Sandbox Code Playgroud)
http://play.golang.org/p/9DdhYduX7E
小智 6
您可以使用reflect.
import (
"reflect"
"math"
)
func foo () {
table := make(map[uintptr] string)
table[reflect.ValueOf(math.Sin)] = "Sin"
table[reflect.ValueOf(math.Cos)] = "Cos"
println(table[reflect.ValueOf(math.Cos)])
}
Run Code Online (Sandbox Code Playgroud)