doulangchao8934 2015-09-14 16:22
浏览 22
已采纳

变异映射中不存在的键与数组中相似的键

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:

package main

import "fmt"

func main() {
    a := make([]int, 10)
    fmt.Println(a[123]) //panic: runtime error: index out of range, good

    b := make(map[int]int, 10)
    fmt.Println(b[123]) // 0 ? WHAAAT? Not nil, not panic?
}

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

v, ok := b[11]
if (!ok) {
    // do something strange
}

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?

  • 写回答

2条回答 默认 最新

  • duansan9435 2015-09-14 16:31
    关注

    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.

    func mapSafe(m map[string]int, key string) (i int) {
        i, ok: = m[key]
        if (!ok) {
            panic("Key not in map")
        }
        return
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条