When reading kubernetes code, sometimes you will see some code compares arrays to nil.

1
2
3
4
5
6
7
8
9
// bindAPIUpdate gets the cached bindings and PVCs to provision in podBindingCache
// and makes the API update for those PVs/PVCs.
func (b *volumeBinder) bindAPIUpdate(podName string, bindings []*bindingInfo, claimsToProvision []*v1.PersistentVolumeClaim) error {
    if bindings == nil {
        return fmt.Errorf("failed to get cached bindings for pod %q", podName)
    }
    if claimsToProvision == nil {
        return fmt.Errorf("failed to get cached claims to provision for pod %q", podName)
    }

It is necessary to clarify the initialization method of arrays.

In Golang, an empty array can be declared in the following two ways.

1
var t []string

or

1
t := []string{}

The length of the array initialized in both cases is 0, but the value of t is not always nil.

Try it out

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.

1
var a0 []int = make([]int, 0)

Try it out

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: