4

In Go, is it idiomatic to check for nil and return an error if a parameter is nil?

Should pointer method receivers ever include nil checks?

I've seen a lot of code in other languages where people applying defensive programming also checked for nulls and threw an exception when a null was passed in. I am wondering if the Go-equivalent, checking for nil and returning an error, is idiomatic in Go. Say some function returns nil for some reason and you pass in nil into another function. This function doesn't handle nils and somewhere down the stack inside of the function a "kaboom" occurs, leaving the caller wondering whether the error is inside of the abstraction or in his calling code.

enderland
  • 12,201
  • 4
  • 53
  • 64
sqroot
  • 49

1 Answers1

2

Checking for nil, and returning an error is not a pattern I have seen in Go (I have been using it professionally for about 6 months at the moment).

If a function that does not allow nil, e.g. a pointer method receiver, is called with a nil value, that is a programming error - and when an error is caused by something that is a programming error I think that the idiomatic solution is to panic which is actually what will happen when the pointer is dereferenced.

As an example in the go library, the reflect package has plenty of methods that can panic when called incorrectly. E.g. Value.Float() will panic if the Value instance does not refer to a floating point value.

error return values are, from what I can tell, not so much to communicate programming errors, but rather situations happening outside the control of your application, e.g. cannot connect to database, file cannot be written to, network connection lost, etc.

I have certainly not checked the receiver in pointer method receivers in the Go code I have written.

Pete
  • 9,016