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 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?