Golang如何使用函数作为map的键
发布时间:2020-12-16 19:23:22 所属栏目:大数据 来源:网络整理
导读:如何使用函数作为map的键?例如: type Action func(int)func test(a int) { }func test2(a int) { }func main() { x := map[Action]bool{} x[test] = true x[test2] = false} 这些代码会显示错误:无效的映射键类型操作 你可以使用反射. import ( "reflect"
如何使用函数作为map的键?例如:
type Action func(int) func test(a int) { } func test2(a int) { } func main() { x := map[Action]bool{} x[test] = true x[test2] = false } 这些代码会显示错误:无效的映射键类型操作
你可以使用反射.
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)]) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |