关于nil的理解

  Go源码({Go安装目录}/src/builtin/builtin.go)对于nil的说明如下:
 
  nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.
 
  翻译成中文就是:nil是一个预先声明的标识符,表示指针、管道、函数、接口、映射或切片类型的零值。

  关于nil的定义可以直接看builtin.go

// nil is a predeclared identifier representing the zero value for a
// pointer, channel, func, interface, map, or slice type.
var nil Type // Type must be a pointer, channel, func, interface, map, or slice type

// Type is here for the purposes of documentation only. It is a stand-in
// for any Go type, but represents the same type for any given function
// invocation.
type Type int

  从源码可知,nil其实就是一个数据类型为Type的变量,而Type必须是指针、管道、函数、接口、映射或切片类型。

Copyright © 2024 码农人生. All Rights Reserved