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[]
    
    评论

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊