Golang如何使用函数作为map的键

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

Tor*_*sen 12

您不能将函数用作映射键.该语言规范明确表示:

必须为键类型的操作数完全定义比较运算符==和!=; 因此,键类型不能是函数,映射或切片.


Den*_*ret 7

您不能将函数用作映射中的键:键类型必须具有可比性.

来自Go博客:

地图键可以是任何可比较的类型.语言规范精确定义了这一点,但简而言之,类似的类型是布尔值,数字,字符串,指针,通道和接口类型,以及仅包含这些类型的结构或数组.值得注意的是,列表中没有切片,贴图和函数 ; 这些类型无法使用==进行比较,也不能用作映射键

您可以使用的是一个界面,具体取决于您的精确用例.


小智 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

  • 这只有效,因为您使用的是变量的地址,这与“函数指针”不同。这是将相同函数分配给另一个变量的示例,结果映射有两个条目,因为变量地址不同:https://play.golang.org/p/8DBIR4h1jU (2认同)

小智 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)