Get error with compare array with nil

declare an array and then check if it is nil, and surprisingly get error. any idea? Thanks!

package main

import (
	"fmt"
)

func main() {
	var array1 [2]int
	if array1 != nil {
		fmt.Println("yes")
	}else{
		fmt.Println("no")
	}
}

error:

# command-line-arguments
./slice1.go:9:12: cannot convert nil to type [2]int
2 Likes

An array never gets nil. In fact, when you declare a array you give it its length and then golang inits it to zero value of the type of the array. For example in this case it creates a two array of int and init it with 0 ([0 0]
var array1 [2]int
fmt.Printf("%v\n%d", array1, len(array1))

An slice, in other side, could be nil

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.