Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for nil and nil interface in Go

Tags:

go

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.

like image 395
Era Avatar asked Nov 20 '12 15:11

Era


People also ask

How can I tell if an interface is nil?

There are two things: If y is the nil interface itself (in which case y==nil will be true), or if y is a non-nil interface but underlying value is a nil value (in which case y==nil will be false).

Can a Golang interface be nil?

Under the hood, an interface in Golang consists of two elements: type and value. When we assign a nil integer pointer to an interface in our example above, the interface becomes (*int)(nil) , and it is not nil. An interface equals nil only if both the type and value are nil.

Is nil null in Go?

nil is a frequently used and important predeclared identifier in Go. It is the literal representation of zero values of many kinds of types. Many new Go programmers with experiences of some other popular languages may view nil as the counterpart of null (or NULL ) in other languages.

What is nil pointer in Golang?

In the Go programming language, nil is a zero value. Recall from unit 2 that an integer declared without a value will default to 0. An empty string is the zero value for strings, and so on. A pointer with nowhere to point has the value nil . And the nil identifier is the zero value for slices, maps, and interfaces too.


2 Answers

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.

like image 196
zzzz Avatar answered Sep 18 '22 11:09

zzzz


If neither of the earlier options works for you, the best I could came up so far is:

if c == nil || (reflect.ValueOf(c).Kind() == reflect.Ptr && reflect.ValueOf(c).IsNil()) 

At least it detects (*T)(nil) cases.

like image 37
aaa bbb Avatar answered Sep 19 '22 11:09

aaa bbb