在可变映射中不存在的键与数组中的类似之处

huangapple go评论125阅读模式
英文:

Non-existent keys in mutating maps vs similar in arrays

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是一个Go语言的新手,Go之旅中关于修改映射的部分让我感到困惑。

这里是问题的一个例子:

  1. package main
  2. import "fmt"
  3. func main() {
  4. a := make([]int, 10)
  5. fmt.Println(a[123]) //panic: runtime error: index out of range, good
  6. b := make(map[int]int, 10)
  7. fmt.Println(b[123]) // 0 ? 什么情况?不是nil,也不是panic?
  8. }

我知道,我可以通过第二个返回值来检查元素是否存在,像这样:

  1. v, ok := b[11]
  2. if (!ok) {
  3. // 做一些奇怪的事情
  4. }

但为什么我需要在每次需要从映射中获取值的地方都这样做呢?我认为映射就像是关联数组,但这种行为真的很奇怪。

我该如何创建一个具有panic级别的键检查的映射呢?

英文:

I'm a newbie in golang and this part of a tour of Go about mutating maps is killing my world of pink ponies.

Here is an example of the problem:

  1. package main
  2. import "fmt"
  3. func main() {
  4. a := make([]int, 10)
  5. fmt.Println(a[123]) //panic: runtime error: index out of range, good
  6. b := make(map[int]int, 10)
  7. fmt.Println(b[123]) // 0 ? WHAAAT? Not nil, not panic?
  8. }

I know, that I can check element existence with second value, like this:

  1. v, ok := b[11]
  2. if (!ok) {
  3. // do something strange
  4. }

But why I need to do this every time in every place where I need to get something from map? I consider maps like associative arrays, but this behavior is really strange.

How can I make a map with panic-level checking of keys?

答案1

得分: 3

唯一确定地判断一个 map 中的零值是否是由于键不存在的方法是使用 "comma, ok" 惯用法 (v, ok := m[k])。如果你需要对不存在的键做出 panic 响应,最好的方法是编写一个辅助函数。

  1. func mapSafe(m map[string]int, key string) (i int) {
  2. i, ok := m[key]
  3. if (!ok) {
  4. panic("Key not in map")
  5. }
  6. return
  7. }
英文:

The only way to be certain that a zero value from a map isn't due to the key not existing is the "comma, ok" idiom (v, ok := m[k]). If you need a panic response to a non-existent key, the best route is to write a helper function.

  1. func mapSafe(m map[string]int, key string) (i int) {
  2. i, ok: = m[key]
  3. if (!ok) {
  4. panic("Key not in map")
  5. }
  6. return
  7. }

答案2

得分: 1

你无法制作一个具有 panic-level 键检查的地图。

英文:

> How can I make a map with panic-level checking of keys?

You cannot.

huangapple
  • 本文由 发表于 2015年9月15日 00:22:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/32569479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定