Check for nil and nil interface in Go

go

Solution

See for example Kyle's answer in this thread at the golang-nuts mailing list.

In short: If you never store `(*T)(nil)` in an interface, then you can reliably use comparison against nil, no need to use reflection. On the other hand, assigning untyped nil to an interface is always OK.

Problem

Currently I'm using this helper function to check for nil and nil interfaces ``` func isNil(a interface{}) bool { defer func() { recover() }() return a == nil || reflect.ValueOf(a).IsNil() } ``` Since `reflect.ValueOf(a).IsNil()` panics if the value's Kind is anything other than `Chan`, `Func`, `Map`, `Ptr`, `Interface` or `Slice`, I threw in the deferred `recover()` to catch those. Is there a better way to achieve this check? It think there should be a more straight forward way to do this.

Original source