doufang7385 2016-12-11 19:01
浏览 241

为什么在golang中打印(nil)映射会产生非“ <nil>”结果?

In golang, if you create a struct with a map in it, which is uninitialized, printing the map yields a non <nil> string.

Why does "print" of a nil map output "map[]" instead of <nil> ?

// Assume above there is a struct, a.AA, which is created but which otherwise
// has not created the map.
//output:
//map[]
//map[]
fmt.Println(a.AA)
fmt.Println(make(map[string]int64))
  • 写回答

2条回答 默认 最新

  • duandu1966 2016-12-11 20:53
    关注

    A nil pointer is not the same as an empty (or zero) map. See https://golang.org/ref/spec#The_zero_value for authoritative information concerning zero values.

    If you want a nil, you need a pointer, such as in the following example:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        var myMap map[string]int64
        fmt.Printf("myMap before assignment: %v
    ", myMap)
    
        myMap = make(map[string]int64)
        fmt.Printf("myMap after assignment : %v
    ", myMap)
    
        var myMapPointer *map[string]int64
        fmt.Printf("myMapPointer before assignment: %v
    ", myMapPointer)
    
        myMapPointer = new(map[string]int64)
        fmt.Printf("myMapPointer after assignment : %v
    ", myMapPointer)
    }
    

    This gives:

    myMap before assignment: map[]
    myMap after assignment : map[]
    myMapPointer before assignment: <nil>
    myMapPointer after assignment : &map[]
    
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真