此文转载自本人微信公众号:lishinho杂货铺 欢迎大家关注
今天的每日一题:
package main
import "fmt"
func main() {
if []int32{} == nil {
fmt.Println("[]int32{} is nil")
} else {
fmt.Println("[]int32{} is not nil")
}
}
答案是:
fmt.Println("[]int32{} is not nil")
是不是很简单?今天主要拓展讲下nil的含义
一,在golang中什么是nil
nil在golang中代表空值,不过nil并没有类型,这就导致你只能预定义nil的类型,不能先赋值nil再进行推倒,比如var b = nil就是错误的
二,切片的nil
之前也介绍过,一个slice由3部分组成,pointer,len和cap。
当pointer是nil,len和cap都是0的时候,这个slice等于nil. 像今天的这道题,很明显[]int32{}是一个切片类型(type slice),它的指针是指向底层int32类型的一个空数组(但是不代表指针为nil),所以这个切片自然也不是nil。
三,指针及其他类型的nil
nil pointer是一个没有指向任何值的指针,它的值是 0x0.
我们可以手动制造出一个空指针:
var a = (*int32)(unsafe.Pointer(uintptr(0x0)))
print(a == nil) //true
其余所有的数据结构的nil都可以看成是指针nil的包装体,比如channel和map的nil
其实和切片相似,channel和map也是一个指针指向一堆implementation. 我们完全可以把它看成一个指针,这个指针是nil,那就是nil了。
其他包括interface和包装类型也是这样,interface以及在上期中讲过,这次补充一个例子:
error其实也是一个interface,在do()中err被赋予了一个指针类型,指向的值为nil,但本身err并不是nil,需要辨别。
// The error built-in interface type is the conventional interface for// representing an error condition, // with the nil value representing no error.
type error interface {
Error() string
}