errors.Is in Go
Comparing against a sentinel through any amount of wrapping.
var (
ErrLocked = errors.New("step locked")
ErrMissing = errors.New("step missing")
)
func play(idx int) error {
if idx > 10 {
return fmt.Errorf("play %d: %w", idx, ErrMissing)
}
if idx > 3 {
return fmt.Errorf("play %d: %w", idx, ErrLocked)
}
return nil
}
func describe(idx int) string {
err := play(idx)
switch {
case err == nil:
return "playing"
case errors.Is(err, ErrLocked):
return "earn a star first"
case errors.Is(err, ErrMissing):
return "no such step"
}
return "unknown failure"
}
How it works
==fails once the error is wrapped;errors.Isdoes not.- Sentinels are exported vars so callers can name them.
errors.Isalso matches an Is method you define.
Keywords and builtins used here
caseerrorfuncifintreturnstringswitchvar
The run, in numbers
- Lines
- 27
- Characters to type
- 493
- Tokens
- 115
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 69 seconds.
Step 2 of 4 in Wrapping, step 5 of 15 in Errors.