在工作中遇到了一个关于 []struct 和 nil的一个 bug,发现 nil 和我想象中的概念不是很一样。
那么 nil 在 go 中是怎么样的一个存在?可以和空指针直接挂等号吗?

go nil 代表什么?

go nil is the zero value for some types, representing uninitialized value.
stackoverflow answer

go nil 可以作用在哪些类型上?

nil can represents pointers, interfaces, slices, maps, channels and functions.
can not represents other basic data type in go.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fmt.Println("nil test: ")
// var a string = nil
// cannot use nil as type string in assignment
var a map[int]int = nil
if a == nil {
fmt.Println("map can be nil")
fmt.Println(reflect.TypeOf(a))
}

var b chan int = nil
if b == nil {
fmt.Println("chan can be nil")
fmt.Println(reflect.TypeOf(b))
}

var c interface{} = nil
if c == nil {
fmt.Println("interface can be nil")
fmt.Println(reflect.TypeOf(c))
}

go nil 的类型是什么?

nil 是可以有类型的。
如上个示例。
但 nil 不是 type, 比如不能作为 map 的 key/value 值。