英文:
How to tell if the value of a map is undefined in Go?
问题
假设我有一个像这样的映射:
m := map[string]interface{}{}
现在我得到一个字符串"a",我想知道m["a"]中是否有值,我该如何判断?
目前我看到,m["a"]永远不会是nil,所以我不能将其与nil进行比较以查看是否有值。此外,也没有一个名为undefined的关键字可以用来判断。
英文:
Suppose I have a map like:
m := map[string]interface{}{}
Now I get a string "a", I want to know if there's value in m["a"], how can I tell?
As I can see now, m["a"] is never nil, so I can't compare it to nil to see if there's anything. Also, there's not a keyword named undefined to do that..
答案1
得分: 4
map的访问返回两个值,第二个值是一个布尔值,告诉你是否存在该值。
你可以使用以下标准习语:
if elm, ok := m["a"]; ok {
// 存在元素
} else {
// 不存在元素
}
英文:
map access returns two values, the second one being a boolean telling you if there's a value.
You can use this standard idiom :
if elm, ok := m["a"]; ok {
// there's an element
} else {
// no element
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论