Hacker News new | ask | show | jobs
by jerf 4913 days ago
That is incorrect. Certain types can be nil, and those types have a zero value of nil, but nil is not equal to the zero value for all types. You don't have a "empty array" there, you have an uninitialized slice, with no corresponding array at all, empty or otherwise. Uninitialized slices are nil, but that is not generally true, only for the specified types. If you initialize it, even to an actual "0 array" (as close as we can get), it ceases to be nil. See http://golang.org/ref/spec#The_zero_value , and w.r.t. the tour code, switch it to:

    package main

    import "fmt"

    func main() {
    	var z []int = make([]int, 0, 0) // jerf changed this line
    	fmt.Println(z, len(z), cap(z))
    	if z == nil {
    		fmt.Println("nil!")
    	} else {
    		fmt.Println("initialized slice is not nil")
    	}
    	
    	// This won't even compile; "cannot convert nil
    	// to type int" at the if clause:
    	// var a int = 0
    	// if a == nil {
    	//	fmt.Println("jerf is wrong; nil does == 0")
    	// }
    }
(Oh, and for those that don't know, on the other end of that tour link is the live Go tutorial, which allows you to run arbitrary Go code in your browser. You can fiddle with this live, with no installation of Go.)