我想在 Go 中有一个类似 Map.containsKey()
的函数,因为 Go 本身不提供这种功能,我是否可以有一个自定义函数,如 MapContainsKey(someMap map[K]V, key K)
在 Go 中?
我不知道如何实现它,因为据我所知 Go 中还没有泛型。
我知道我能做到
if val, ok := someMap[key]; ok{
// some code here
}
但我想将它包装在一个函数中。
最佳答案
您可以创建一个使用反射的函数并且是“通用的”,但它会更慢。在 Go 中,您只需编写已有的内容即可。干净,快速,可读。 Go 不是 Java。
为了演示,下面是它的样子。类型检查被省略(例如,如果你传递一个非 map ,或者你传递一个类型与 map 的键类型不匹配的键值,它会 panic ):
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
关于dictionary - 我可以有检查键是否在 map 中的功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62652236/