Home >Backend Development >Golang >A brief analysis of nil and zero values in Golang
As a long-time Java developer, I am obsessed with null checking and handling null values. In golang, the story is a little different. In this post, I will try to describe how to use nil
and zero value
in golang.
Types in go can be empty or non-empty. A non-null type can never be nil, and will never cause you to cause a nil-panic
(equivalent to Java's nullpointerexception) Although not as much as in java (or other languages with null types) We still have to be a little cautious when dealing with empty types.
Non-null basic types
In go, basic types cannot be null. A declaration like
var a int = nil
fails to compile because int
can never be nil. The default value of an unallocated int
type is 0.
Run Statement
var a int // int类型的默认值不能为nil fmt.Println(a) // 0
will output the default value of int
"0
". We call this the zero value of the type.
Same as int
The default is 0, the following are other basic types whose default value is zero:
Types | Zero value |
---|---|
int, int8, int16, int32, int64 | 0 |
0 | |
0 | |
0.0 | |
0 | |
0 | |
"" (empty string) | |
(0,0i) | |
array of zero-values | |
array of nil-values |
The above is the detailed content of A brief analysis of nil and zero values in Golang. For more information, please follow other related articles on the PHP Chinese website!