> On Mon, May 7, 2012 at 9:55 AM, Tom Vogel <voge...@gmail.com> wrote:
>>
>> In this contrived example:
>>
>> http://play.golang.org/p/uVOq8hq5Jn
>>
>> in Storage's implementation of Find it returns the result of calling a
>> function that returns a pointer to a type that satisfies the User
>> interface. But when you compare the result with nil, it says it is
>> not nil (even though the underlying pointer is nil).
Because you're comparing an interface value to nil, you're seeing
if the interface is nil, not whether a pointer it happens to contain
is nil. (After all, the interface might not have a pointer value in it
at all.)
Consider two pointer types *A and *B that satisfy some interface I.
Suppose V is a variable of type I, and we write
V = (*A)(nil)
The value stored inside V is nil, but V is not nil and you can recover
the type of the nil that it contains (with sufficient determination).
>> For AnotherFind, it checks the result of calling the function and
>> returns nil if the result is nil, and this works.
AnotherFind calls lookupId, which returns a pointer, and compares
that pointer -- not an interface -- to nil.
>> My question is: what is the best way to compare an interface to nil?
someInterface == nil
>> I'd prefer to write my code like the Find function and not like the
>> AnotherFind function. But I'd like to be able to compare the result
>> with nil...
You're working with interfaces: you shouldn't be worrying about
what the type is of values inside the interface (unless you /need/ to).
func AssertNotNil(o interface{}) {
if o == nil {
println("nil")
}
}
var x *int = nil
AssertNotNil(x) // doesn't work
Any way to implement this?
This discussion seems to imply that I cannot write the following method without reflection. Is this correct? The goal is to test an abitrary object for nil.
Any way to implement this?
func (usr *User) Exists() bool {
return usr != nil
}