duanluwei9374 2019-01-28 17:14
浏览 46
已采纳

当键不在地图中时不引发错误(例如Python)的好处是什么? [关闭]

In Go, let m is map object that map string to int, suppose "foo" is not a key of m, then the statement

m["foo"]

returns two value 0 and false which false implies "foo" is not a key of m. Could you give some situations, examples that the go's property is useful?

  • 写回答

2条回答 默认 最新

  • dongsuo0517 2019-01-28 17:17
    关注

    Go does not raise errors. Go reports errors.


    A common use of a map element zero value:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        counts := map[string]int{}
        fmt.Println(counts)
    
        // Equivalent:
        // counts["foo"] = counts["foo"] + 1
        // counts["foo"] += 1
        // counts["foo"]++
    
        counts["foo"]++
        fmt.Println(counts)
    
        counts["foo"]++
        fmt.Println(counts)
    }
    

    Playground: https://play.golang.org/p/nvHBrgV_lFU

    Output:

    map[]
    map[foo:1]
    map[foo:2]
    

    A common use of the comma, ok form map index expression:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        m := map[string]map[string]int{}
        fmt.Println(m)
    
        // panic: assignment to entry in nil map
        // m["K1"]["K2"]++
    
        _, ok := m["K1"]
        if !ok {
            m["K1"] = map[string]int{}
        }
        m["K1"]["K2"]++
        fmt.Println(m)
    
        m["K1"]["K2"]++
        fmt.Println(m)
    }
    

    Playground: https://play.golang.org/p/9byxSSIWBre

    Output:

    map[]
    map[K1:map[K2:1]]
    map[K1:map[K2:2]]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块