In go you need to remember two points when it comes to interface nil values:
- A nil interface value, which contains no value at all is not the same as an interface value containing a value that happens to be nil.
- An interface holding a nil value is not nil
Example explaining 1 & 2:
package main
import "fmt"
func main() {
var i1 interface{}
fmt.Println("a == nil: ", i1 == nil)
var i2 interface{}
var p *int = nil
i2 = p
fmt.Println("b == nil: ", i2 == nil)
}
Output:
a == nil: true
b == nil: false
How it works behind the scenes:
Basically an interface in go consists of two things: a dynamic type and a dynamic value. When you assign any value to a nil *int to an interface, now its dynamic type is *int and dynamic value is nil, and therefore the interface now is non-nil and any comparison with nil would result in a false
An interface equals nil only if both its dynamic type and dynamic value are nil.
In your case:
You need to extract the dynamic value of the interface x before you compare it with a nil.
Refer the below code:
package main
import (
"fmt"
)
func Foo(x interface{}) {
fmt.Println("22, x == nil = ", (x).(*int) == nil)//22, x == nil = true
}
func main() {
var x *int = nil
fmt.Println("11, x == nil = ", x == nil)// 11, x == nil = true
Foo(x)
}
Output:
11, x == nil = true
22, x == nil = true