Comparing an interface value with nil in #golang
package main
import (
"fmt"
"reflect"
)
// This is another way of determining if a variable's value is nil.
// Imagine you have an interface with the following signature:
type recorder interface{}
type myStruct struct{}
// Assume this function has to have this signature.
func object() recorder {
// Let's say this function gets the object by calling a dependency, and receives
// a nil value.
var obj *myStruct
return obj
}
func main() {
obj := object()
fmt.Println("Direct comparison:", obj == nil)
fmt.Println("Compare by reflection:", reflect.ValueOf(obj).IsNil())
// Output:
//
// Direct comparison: false
// Compare by reflection: true
}
package main
import (
"fmt"
"reflect"
)
// See nil_interface_value_example.go
func main() {
fmt.Println(reflect.ValueOf(obj).IsNil() == true)
}