Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nil slice when passed as interface is not nil! Why? (golang)

Tags:

null

go

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?

like image 508
mdwhatcott Avatar asked Jan 30 '14 15:01

mdwhatcott


1 Answers

To add to @justinas' answer, if you need to compare the value inside the interface{} value, you can use reflect.ValueOf.IsNil() method which would report if value inside the interface{} is nil.

func main() {
    var a []int = nil
    var ai interface{} = a

    r1 := a == nil // true
    r2 := ai == nil // false, interface is not nil

    vo := reflect.ValueOf(ai).IsNil() // true, value inside interface is nil!
}
like image 116
Serid Avatar answered Nov 16 '22 03:11

Serid