代码之家  ›  专栏  ›  技术社区  ›  overexchange

在更新该键的值之前,该键是否存在?

go
  •  -1
  • overexchange  · 技术社区  · 4 年前

    在下面的代码中:

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    // scores holds values incremented by multiple goroutines.
    var scores = make(map[string]int)
    
    func main() {
        var wg sync.WaitGroup
        wg.Add(2)
    
        go func() {
            for i := 0; i < 1000; i++ {
                if _, ok := scores["A"]; !ok {
                    scores["A"] = 1
                } else {
                    scores["A"]++
                }
            }
            wg.Done()
        }()
    
        go func() {
            for i := 0; i < 1000; i++ {
                scores["B"]++ // Line 28
            }
            wg.Done()
        }()
    
        wg.Wait()
        fmt.Println("Final scores:", scores)
    }
    

    上面的代码有数据竞争 scores 但是,

    第28行没有给出指令的运行时错误 scores["B"]++ .

    怎么 分数[“B”]++ 在第28行,能够更新密钥的值( "B" )for i=0 ? 因为钥匙( B )地图中不存在 分数

    1 回复  |  直到 4 年前
        1
  •  1
  •   Eli Bendersky    4 年前

    你熟悉吗 with the default (zero) value semantics of Go maps ?

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        var scores = make(map[string]int)
        scores["B"]++
        fmt.Println(scores)
    }
    

    Check this snippet on the playground .


    在这里阅读地图: https://blog.golang.org/maps