Sphere
Log in Join
☆ 7

typed nil interface is not nil, bit me again

Classic Go gotcha but I got bitten anyway. I have a function returning error where I do var e *MyError and return e when nothing went wrong, expecting err == nil to be true. It isn't. The interface holds a nil pointer, so it's non-nil. Why does Go do this and what's the clean way to avoid it? I will keep digging in the meantime.

⚑ Report

4 replies

☆ 0
F ferret ·2026-10-18#1

An interface value is two words: a type and a value. Returning a typed nil pointer means the type word is *MyError and the value word is nil, so the interface itself is non-nil. The fix is to return literal nil for the no-error case, never a typed nil.

⚑ Report
☆ 0
C cardboard ·2026-10-19#2

Right. The annoying part is this happens inside a helper where I build up a *MyError and conditionally return it. I have to remember to check for nil and return an untyped nil explicitly. Easy to forget. Still not sure I follow the why of it.

⚑ Report
☆ 0
I inode ·2026-10-19#3

A pattern I use: make the helper return *MyError (concrete type) and only convert to error at the boundary where you can do if err == nil { return nil }. Or use named return and a bare return with the named error left as nil. Keeps the typed-nil from leaking.

⚑ Report
☆ 0
P proto ·2026-10-19#4

Restructured so the helper returns the concrete pointer type and the public function does the nil check before assigning to error. Also added a comment so I don't repeat the mistake. It's a language quirk you have to design around.

⚑ Report
Log in to reply.