dictionary - 我可以有一个功能来检查一个键是否在地图中?
问题描述
我想要一个像Map.containsKey()
Go 一样的函数,因为 Go 本身不提供这种功能,我可以选择像MapContainsKey(someMap map[K]V, key K)
Go 那样有一个自定义函数吗?
我不知道如何实现它,因为据我所知,Go 中还没有泛型。
我知道我能做到
if val, ok := someMap[key]; ok{
// some code here
}
但我想将它包装在一个函数中。
解决方案
您可以创建一个使用反射并且是“通用”的函数,但它会更慢。在 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
推荐阅读
- ms-access - MS Access 表单从多个(不相关的)表中获取数据
- javascript - 下一个光滑的滑块在图像中不起作用
- javascript - 如何让程序等待按钮单击以转到方法中的下一个循环迭代?[JavaScript]
- c# - Windows 窗体:删除树视图左侧的空白区域
- javascript - 在另一个 HTML 元素中附加 HTML 元素
- excel - vba 匹配函数区分大小写
- hyperledger-fabric - 使用 Hyperledger Caliper 对不同机器中的 Hyperledger 织物进行基准测试
- azure - 在 windows server 2012 上通过 VPN P2S 连接到 Azure 资源
- python - 带有过滤条件的列表迭代
- python - 在python中是否可以处理以各种格式编写的地址并构建地图?