Recipe
Choose how a function reports failure
Use when: you're writing a function that can't always produce its answer, and need to pick its return type
Goal: a panic, a Result or an Option, chosen by who can respond to the failure
Taught in Panic or Result?
Quick recipe
-
1
Write down, in words, each way the function can fail to produce its answer.
Example
average(scores): the list might be empty.load_settings(path): the file might be missing or unreadable, or its text might not parse.Why: you can only choose a response once you know what you're responding to.
-
2
For each failure, ask whether it comes from outside the code (a file, input, the network) or can only happen if the code itself is wrong.
- only a code mistake can cause it — panic, with
expectorpanic!and a message saying what should have been true. - it comes from outside and the caller needs to know why — return
Result<T, E>. - "no answer" is ordinary and has one obvious reason — return
Option<T>.
Why: a bug needs a person to change the code; an outside failure needs a response from whoever called.
- only a code mistake can cause it — panic, with
-
3
In the callers, use
?until you reach a function that knows the response, andmatchthere.Why: the function that noticed the failure is rarely the one that knows what the user should see.
-
4
At the top, turn what's left into a message on standard error and an exit status.
Why:
mainis the only place that knows it's talking to a person or a script.
Common mistakes
- Panicking in a library over input the caller couldn't have checked in advance.
- Returning
Resultfor a failure that can only be a bug, so every caller writes amatchfor something that never happens. - Returning
Optionwhen the caller needs to know which of several things went wrong.