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

为什么Go中的地图最初根据地图的大小有空值?

go
  •  1
  • user3226932  · 技术社区  · 6 年前

    给定此代码:

    package main
    
    import "fmt"
    
    type Vertex struct {
        Lat, Long float64
    }
    
    var m []map[string]Vertex
    var m1 map[string]Vertex
    
    func main() {
        m = make([]map[string]Vertex, 3)
        m1 = make(map[string]Vertex)
        m1["Bell Labs"] = Vertex{
            40.68433, -74.39967,
        }
        m = append(m, m1)
        fmt.Println(m)
        fmt.Println(len(m))
        fmt.Println(m[3]["Bell Labs"])
    }
    

    我得到一个输出

    [map[] map[] map[] map[Bell Labs:{40.68433 -74.39967}]]
    4
    {40.68433 -74.39967}
    

    [map[Bell Labs:{40.68433 -74.39967}]] 相反呢?

    1 回复  |  直到 6 年前
        1
  •  8
  •   peterSO    6 年前

    为什么数组中的前3个元素是空/空映射?


    The Go Programming Language Specification

    Making slices, maps and channels

    内置函数make采用T类型,它必须是slice、map 或通道类型,可选后跟 表达。它返回一个T类型的值(不是*T)。记忆是

    Call             Type T     Result
    
    make(T, n)       slice      slice of type T with length n and capacity n
    make(T, n, m)    slice      slice of type T with length n and capacity m
    

    切片 m 属于 map

    m = make([]map[string]Vertex, 3)
    

    m = make([]map[string]Vertex, 3, 3)
    

    应该是

    m = make([]map[string]Vertex, 0, 3)
    

    package main
    
    import "fmt"
    
    type Vertex struct {
        Lat, Long float64
    }
    
    var m []map[string]Vertex
    var m1 map[string]Vertex
    
    func main() {
        m = make([]map[string]Vertex, 0, 3)
        fmt.Println(len(m), cap(m))
        m1 = make(map[string]Vertex)
        m1["Bell Labs"] = Vertex{
            40.68433, -74.39967,
        }
        m = append(m, m1)
        fmt.Println(m)
        fmt.Println(len(m), cap(m))
        fmt.Println(m[0]["Bell Labs"])
    }
    

    游乐场: https://play.golang.org/p/i9f0rrCrtY_5

    输出:

    0 3
    [map[Bell Labs:{40.68433 -74.39967}]]
    1 3
    {40.68433 -74.39967}