Go Developer interview question

Why can a Go interface be non-nil with a nil value?

An interface value is nil only when both its dynamic type and dynamic value are nil. A typed nil pointer stored in an interface has a dynamic type, so the interface itself is non-nil.

Direct answer

What a strong answer covers

How it works

An interface value holds two words: a dynamic type and a dynamic value. Assigning a typed nil pointer fills the type word, so the comparison err != nil is true even though calling a method through it may dereference nil. The confusion appears whenever a function declares an interface return type but builds the result from a concrete pointer variable.

Example

var p *MyError = nil; var err error = p makes err != nil. Return a literal nil interface when there is no error: write return nil rather than return p, or check the concrete pointer before converting it to the interface type.

Common mistakes

  • Returning a nil concrete pointer through an error return type.
  • Comparing an interface to nil to decide whether the underlying pointer is nil.
  • Storing typed nil values in a slice of interfaces and treating them as absent.

A useful answer structure

Answer from your own work.

Do not memorise a script: use only examples you can explain honestly in follow-up questions.

Practise this answer with MiraHint

Open the desktop workspace and rehearse a clear answer in your own words.

Download MiraHint
Go Developer interview questions