Well no - the error I get is that I am attempting to call String() method on a null receiver - so the caller just passed me a regular nil object. The issue is that I am trying to make a generic polymorphic function which should be able to handle whatever is thrown at it - so I guess reflect is necessary.
I think I am supposed to detect the null receiver before calling String() on it. I ended up using this little utility: https://stackoverflow.com/questions/13476349/check-for-nil-and-nil-interface-in-go func isNil(a interface{}) bool { defer func() { recover() }() return a == nil || reflect.ValueOf(a).IsNil()} But this feels really hacky when I really just want to say if value != nil { ....} . Thanks Michael. On Wednesday, 9 May 2018, Jakob Borg <ja...@kastelo.net> wrote: > On 8 May 2018, at 15:26, scude...@gmail.com wrote: > > But this crashes when foo is really a nil pointer to a type which does > support Stringer. > > > The crash isn’t on “your” side though, it’s presumably inside the String() > method. Hence, the caller passed you something invalid that you can’t > handle. I’d argue that avoiding this is their responsibility. > > My case is made weaker by how fmt.Println and friends handle this though. > They’ll call the String() method, recover from the panic, use reflect to > see if the boxed value is nil, and print a “<nil>”. I guess this is > friendly, but not something I think normal code should do. > > (In your specific case you seem to be reimplementing fmt.Sprint; you can > just use that instead. :) > > //jb > -- 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.