首页 > 解决方案 > 我可以有一个功能来检查一个键是否在地图中?

问题描述

我想要一个像Map.containsKey()Go 一样的函数,因为 Go 本身不提供这种功能,我可以选择像MapContainsKey(someMap map[K]V, key K)Go 那样有一个自定义函数吗?

我不知道如何实现它,因为据我所知,Go 中还没有泛型。

我知道我能做到

if val, ok := someMap[key]; ok{
   // some code here
}

但我想将它包装在一个函数中。

标签: dictionarygo

解决方案


您可以创建一个使用反射并且是“通用”的函数,但它会更慢。在 Go 中,您只需编写已有的内容。干净,快速,可读。Go 不是 Java。

为了演示,下面是它的样子。省略类型检查(例如,如果您传递非映射,或者您传递类型与映射的键类型不匹配的键值,则会出现恐慌):

func containsKey(m, k interface{}) bool {
    v := reflect.ValueOf(m).MapIndex(reflect.ValueOf(k))
    return v != reflect.Value{}
}

测试它的示例:

m1 := map[string]int{"one": 1, "x": 0}
fmt.Println(containsKey(m1, "one"))
fmt.Println(containsKey(m1, "x"))
fmt.Println(containsKey(m1, "two"))

m2 := map[int]string{1: "one", 9: ""}
fmt.Println(containsKey(m2, 1))
fmt.Println(containsKey(m2, 9))
fmt.Println(containsKey(m2, 2))

输出(在Go Playground上试试):

true
true
false
true
true
false

推荐阅读