This is a creation in Article, where the information may have evolved or changed.
This article is Francesc Campoy on the GoConf
Understanding Nil Lecture notes.
(1) nil
no type
.
(2) in a Go
language, variables that do not appear to be initialized have their type zero value
. 6
the common types of variables zero value
are:,,, nil
pointer
slice
map
channel
, function
and interface
. The specific meanings are as follows:
type |
Nil value meaning |
Pointer |
Point to Nothing |
Slice |
3 member values in the slice variable: buf is nil (no backing array), Len and Cap are all 0 |
Map,channel,function |
A nil pointer, pointing to Nothing |
Interface |
Interface contains "type, value", and a nil interface must both be nil: "Nil, nil" |
For that interface
reason, the value is just because <type, value>
two values in this tuple are needed nil
interface
nil
. So pay attention to the following two points:
A) do not declare concrete error VARs:
func do() error { var err *doError // nil of type *doError return err // error (*doError, nil)}func main() { err := do() // error (*doError, nil) fmt.Println(err == nil) // false}
b) do not return concrete error types:
func do() *doError { return nil // nil of type *doError}func main() { err := do() // nil of type *doError fmt.Println(err == nil) // true}func do() *doError { return nil // nil of type *doError}func wrapDo() error { // error (*doError, nil) return do() // nil of type *doError}func main() { err := wrapDo() // error (*doError, nil) fmt.Println(err == nil) // false}
(3) nil
Some useful usage scenarios:
type |
Nil Value usage scenario |
Pointer |
Methods can called on nil receivers |
Slice |
Perfectly valid zero values |
Map |
Perfect as read-only values (adding members to nil map will cause panic) |
Channel |
Essential for some concurrency patterns |
function |
Needed for completeness |
Interface |
The most used signal in Go (err! = nil) |