duangan4070 2019-05-10 06:20
浏览 33
已采纳

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

Hoping to understand maps in Go better.

Given this code:

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"])
}

I get an output of

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

Why is it that the first 3 elements in the array are empty/null maps, shouldn't it print out [map[Bell Labs:{40.68433 -74.39967}]] instead?

  • 写回答

1条回答 默认 最新

  • dongxing5525 2019-05-10 06:32
    关注

    Why is it that the first 3 elements in the array are empty/null maps?


    The Go Programming Language Specification

    Making slices, maps and channels

    The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T). The memory is initialized as described in the section on initial values.

    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
    

    The slice m of map

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

    is equivalent to

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

    it should be

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

    For example,

    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"])
    }
    

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

    Output:

    0 3
    [map[Bell Labs:{40.68433 -74.39967}]]
    1 3
    {40.68433 -74.39967}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境