On Tue, May 8, 2018 at 7:19 AM, Michael Cohen <scude...@gmail.com> wrote: > > 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 { > ....} .
I think there may be some confusion here. Go doesn't have a "regular nil object." Specific types can be `nil`. In particular, pointer types can be `nil`. When a type implements a `String` method it is possible to call that method with a `nil` pointer. In general it is possible to call any method with a `nil` pointer. That is not an error. Some specific implementations of a `String` method may panic when called with a `nil` pointer. For better or for worse, the fmt package has special handling for this. What this means is that unless you have some special knowledge of the type you are working with, you should not check for `nil` before calling the `String` method. For some types the `String` method will correctly handle `nil`. If you have types with a `String` method that does not correctly handle `nil`, then it's worth pondering why and how you got a `nil` pointer for this type in the first place. But if you can reasonably have a `nil` pointer, and can reasonably expect that the `String` method will panic in that case, then what you should do is call `fmt.Sprint(v)`. That will do the right thing whether v's `String` method handles `nil` or not. Ian -- 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.