Your function returns nil on the success path, the caller checks err != nil, and the check fires anyway. What happened?
A Go interface is non-nil when it holds a concrete type, even if the concrete pointer value is nil. Returning a typed nil pointer as an error creates an interface value that fails err == nil checks.
Answer
Short answer
In Go, an interface value contains both a dynamic type and a value. If a function returns a typed nil pointer as error, the interface has a type even though the pointer is nil, so err != nil is true. Return a plain nil error instead of a typed nil pointer.
Keep interfaces explicit in the answer because that is the concept the interviewer is actually trying to test. A good interfaces explanation names the trade-off, the failure mode, and the evidence you would use before choosing. Use interfaces once more at the decision point so the answer reads as judgement rather than a detached example.
Keep interfaces explicit in the answer because that is the concept the interviewer is actually trying to test. A good interfaces explanation names the trade-off, the failure mode, and the evidence you would use before choosing.
Was this answer helpful?
Likely follow-ups
- Rewrite the function so the bug is impossible rather than merely absent.
- Why does a nil map read work while a nil map write panics?
- How would errors.As behave against this value?
- Where else does Go compare a two-word value in a way that surprises people?
Related questions
- Go gives you no project layout and no dependency-injection container. How do you structure a service so it stays testable as it grows?mediumAlso on interfaces and golang5 min
- A promise rejects and nothing is awaiting it. What does Node do?hardAlso on error-handling4 min
- Your logs are full of Cannot set headers after they are sent. Walk me through how a request gets into that state.mediumAlso on error-handling4 min
- Several producers write to one channel and one consumer reads it. Who closes the channel?mediumAlso on golang4 min