See this playground: http://play.golang.org/p/nWHmlw1W01
package main
import "fmt"
func main() {
var i []int = nil
yes(i) // output: true
no(i) // output: false
}
func yes(thing []int) {
fmt.Println(thing == nil)
}
func no(thing interface{}) {
fmt.Println(thing == nil)
}
Why the difference in output between the two functions?
Admittedly, it's somewhat of a quirk, but there's an explanation for it.
Imagine an
interface{}
variable as a struct composed of two fields: one is the type and another is the data. ([]int
andnil
). Actually, it looks just like that in the Go runtime.When you pass your nil slice to
yes
, onlynil
is passed as the value, so your comparison boils down tonil == nil
.Meanwhile, calling
no
automatically wraps your variable in aninterface{}
type and the call becomes something akin tono(interface{[]int, nil})
. So the comparison inno
could be seen asinterface{[]int, nil} == nil
, which turns out to be false in go.The issue is actually explained in the Go FAQ.