Go Nil

2021-01-04  本文已影响0人  JunChow520

Go语言数据类型中,布尔类型的零值(初始值)为false,数值类型的零值为0,字符串类型的零值为空字符串""

对于pointer指针、slice切片、map映射、channel通道、function函数、interface接口的零值则为nil

nil是Go语言中预定义的标识符,Go语言中的nil并非等同于其它语言中的null

nil == nil //invalid operation: nil == nil (operator == not defined on nil)
print(nil) // use of untyped nil
var flag bool
var num int
var str string
var arr []int
var p *int

fmt.Printf("flag = %v, type = %T\n", flag, flag)//flag = false, type = bool
fmt.Printf("num = %v, type = %T\n", num, num)//num = 0, type = int
fmt.Printf("str = %v, type = %T\n", str, str)//str = , type = string
fmt.Printf("arr = %v, type = %T, pointer = %p\n", arr, arr, arr)//arr = [], type = []int, pointer = 0x0
fmt.Printf("p = %v, type = %T, pointer = %p\n", p, p, p)//p = <nil>, type = *int, pointer = 0x0
var dict map[string]string
var ptr *int

fmt.Printf("dict = %v, type = %T, pointer = %p\n", dict, dict, dict)//dict = map[], type = map[string]string, pointer = 0x0
fmt.Printf("ptr = %v, type = %T, pointer = %p\n", ptr, ptr, ptr)//ptr = <nil>, type = *int, pointer = 0x0
print(dict == ptr) // invalid operation: dict == ptr (mismatched types map[string]string and *int)

Go语言中mapslicefunction类型的nil值不能比较,比较两个无法比较类型的值是非法的。

一个类型的所有值的内存布局都是一样的,nil的大小与同类型非nil的大小保持一致,但不同类型的nil值的大小可能不同。具体大小取决于编译器和架构。

var dict map[string]string
fmt.Printf("dict = %v, type = %T, pointer = %p, size = %d\n", dict, dict, dict, unsafe.Sizeof(dict))
// dict = map[], type = map[string]string, pointer = 0x0, size = 8
上一篇下一篇

猜你喜欢

热点阅读