Search code examples
goerror-handlingidioms

Is return nil, nil not idiomatic go?


If we have the following method in GO:

GetCustomer(id string) (*Customer, error)

A customer for a given id may not exist in DB. When a customer is not found, the code can

return nil, nil

Is this considered bad coding practice in Go? Or would the idiomatic Go code would look like

 return nil, errCustomerNotFound

The problem I see with the second approach is that you end up checking for this specific error and handling it seperately.

Are there examples in Go source or libraries where this situation arises and one of the approaches is preferred?

Update

If return nil, nil is considered as not idiomatic. I was wondering why that is true in this case? As *Customer is a pointer, I want to return nil to indicate absence of value


Solution

  • Whether return nil, nil is idiomatic in your case or not depends on whether a nil *Customer is a useful value.

    If a nil value for *Customer is a normal, useful value in your code, then returning that, with no error, makes sense.

    It would be rare that a nil struct pointer is useful, though--that alone could be considered non-idiomatic in most cases.

    The rule to follow:

    Every function should always return a useful set of values.

    In your case, where you return a struct pointer and an error, one could reasonably assume that at most one of those would be nil.

    Using a nil struct pointer to indicate the absence of a value can be idiomatic, but not in conjunction with an error. If your function can have only a single error condition of 'not found', you might opt for a function that returns only a single value, which may be nil, or you may opt to return a boolean indicating existence rather than an error.

    But returning a nil to mean "not found" when also including an error is confusing, at best, because it violates the principle of least astonishment.