Rrors.new Do, And When Do You Use
Fast recall
Quick revision
Core answer
Whether you understand Errors New beyond memorized syntax.
Giving a definition without explaining a practical trade-off.
Connect the concept to a small production example and state its complexity or failure mode.
Interview-ready guide
Interview answer
errors.New takes a string and returns an error whose Error() method returns that string. That's all it does — but that gives you a value you can return, compare, and pass around, which is the whole error-as-value contract.
Use it when the error carries no payload: a fixed condition with a fixed meaning. 'queue is full', 'config missing' — states where a string fully describes the failure and no caller needs to extract fields from it. The moment an error needs data — which file, what status code, what retry-after — a string isn't enough, and you want a custom type or fmt.Errorf.
The other major use is sentinel errors: package-level vars like var ErrNotFound = errors.New("not found") that callers can match with errors.Is. Because the package exports one specific value, identity comparison works — the error is both the message and the key.
Rrors.new Do, And When Do You Use
Direct Answer
Creates a simple error value with a fixed message. Use when the error needs no data — just an identity.
Deep Dive & Architecture
What errors.New returns is worth looking at once. Historically it returned a *errorString — a pointer to a struct holding your string:
type errorString struct { s string }
func (e *errorString) Error() string { return e.s }
Two consequences of the pointer:
First, two errors.New calls with identical text are different errors. errors.New("x") == errors.New("x") is false — separate allocations. Equality is identity, which is exactly what sentinel usage wants: only the one exported var matches.
Second, the Error() method on the pointer means errors.Is comparisons are pointer comparisons — cheap and exact. When Go 1.21 added errors.ErrUnsupported and friends, they were created with errors.New for exactly this identity semantics.
That's the whole mental model: errors.New is the minimal error — an identity plus a message, nothing more, ideal when 'which error' matters more than 'what details'.
Common Mistakes & Pitfalls
Giving a definition without explaining a practical trade-off.
Check your understanding
Answer these without looking back at the article.
- When would you use Errors New in a real project?
- How would you compare Errors New with an alternative?
- What is a common mistake when using Errors New?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.