When reading kubernetes code, sometimes you will see some code compares arrays to nil.
|
|
It is necessary to clarify the initialization method of arrays.
In Golang, an empty array can be declared in the following two ways.
|
|
or
|
|
The length of the array initialized in both cases is 0, but the value of t is not always nil.
As you can see, only the first way of declaring t is nil.
The second way, t actually points to an empty array. This way of declaration is similar to the following way.
|
|
Golang officially recommends the first method when declaring a null array; however, everything is not absolute, and the latter two methods are recommended when encoding in JSON, because a nil null array will be encoded to null, but a non-nil null array will be encoded to the JSON array [], making it easier for the front-end to parse.
a nil slice encodes to null, while []string{} encodes to the JSON array [].
Golang officially does not recommend that the interface return value distinguish whether the array is nil or not, which may cause some minor problems.
Ref: