Good morning!

I realize I'm reviving an age-old discussion here and apologize for 
bringing up the undead. I happend to run into this when my application 
panicked when some interfaces where initialized with nil mock objects 
instead of being left uninitialized as in production mode.

Axel said:

Checking "x == nil" is the correct way to check whether a value contains a 
> valid implementation of an interface - and a nil-pointer with the correct 
> method set is, as far as you should be concerned, such a valid 
> implementation.
>
 
This would be an example where a nil implementing fooer is never caught:

type fooer interface {
 foo()
}

type other struct{}

func (o *other) foo() {} // implement fooer

func main() {
 var f fooer

 var p *other // nil
 f = p // it is a fooer so I can assign it

 if f == nil {
    // will not get here
 }
}


My confusion comes from the point that the nil interface is apparently not 
"a nil-pointer with the correct method set" while *other is even if nil.

If you indeed want to check whether the contained value is a nil-pointer 
> (I'm having actual trouble coming up with a scenario where you'd want to do 
> that - except cases like encoding/json, where you need to use reflection 
> anyway), you have to check that explicitly, either by converting nil into 
> the correct type (i.e. "x == (*T)(nil)"), or by type-asserting. That is the 
> uncommon case, so it's fine having to jump through a couple of hoops for 
> hat.
>

The above is a case where that might happen. In can be worked around but it 
is unexpected unless the programmer is deeply rooted in the language 
definition.
 

> What *might* make more sense, is trying to lint whether a nil-pointer is 
> used for an interface, and the corresponding methods are not nil-safe. I.e. 
> do the "is a nil-pointer a valid value for this interface" check where it 
> belongs: At the point where the interface-conversion happens (when 
> assigning it to an interface-typed variable or passing it as an 
> interface-typed parameter).


Seems as of today that there is no tooling to support that check. Maybe 
it's not a widespread issue. 

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/e0dbcd38-510e-43b9-b363-2af1c636250b%40googlegroups.com.

Reply via email to