In my case, being a new go learner the following bit of code stumped me. I 
am receiving a interface{} value and I am trying to figure out the best way 
to print it. If the value supports the fmt.Stringer() interface then I want 
to use that, otherwise i can do some other things. So I came up with this:

func printer(foo interface{}) string {

     switch t := foo.(type) {
     ....
     case fmt.Stringer:
             return t.String()
      ...
}

But this crashes when foo is really a nil pointer to a type which does 
support Stringer. The problem is that there is no way for me to actually 
know foo is nil and avoid it. I can not compare foo to nil because foo is 
an interface so foo==nil is false, and my type assertion is converting it 
to an interface too so i can not compare that to nil either. Literally the 
only way this code can work is to just catch the error and return the 
string "nil". This is hugely confusing behavior especially for a new comer.

Apart for this it seems to me the natural way to implement this kind of 
code - for example in python the code is natural, and I wanted to carry the 
same general technique to go:

def printer(foo):
   if isinstance(foo, Stringer):
     return foo.String()
  ...

Thanks
Michael.



On Tuesday, June 5, 2012 at 8:50:00 AM UTC+10, jgoldbg wrote:
>
> I'm a bit stumped and wondering if I'm overlooking some way, besides 
> reflection, 
> to determine whether the data pointed at by an interface{} is actually a 
> nil 
> pointer: 
>
>     http://play.golang.org/p/Isoo0CcAvr 
>
> Any ideas what I'm overlooking? 
>
> jonathan 
>

-- 
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.
For more options, visit https://groups.google.com/d/optout.

Reply via email to