Result
A panic is the fire alarm for bugs. But what about an ordinary failure you can foresee?
Picture ordering a parcel. The courier comes back in one of two ways: either with the parcel, or with a note saying why it is missing: "address not found", "warehouse closed". Either way you get an answer and decide what to do next. Nobody sets off the alarm because a parcel did not arrive.
Take a task where failure is routine: turning text into a number. The string "42" can be turned into one, while "42a" cannot. The parse method does this:
fn main() {
let good = "42".parse::<i32>();
let bad = "42a".parse::<i32>();
println!("{:?}", good); // Ok(42)
println!("{:?}", bad); // Err(ParseIntError { kind: InvalidDigit })
}Let's walk through the example line by line:
"42".parse::<i32>()reads the string as a number. The angle brackets after::hold the type to turn the text into, herei32."42a".parse::<i32>()compiles too, and the program does not crash: the failure comes back as a value.{:?}prints the first value asOk(42): the courier with the parcel.- The second value prints as
Err(...): the courier with a note. The note says the string contains an invalid character.
Notice that parse reads the whole string. It does not take a number from the start of the string, so "42a" is an error, not 42. A space is an extra character too: " 7" does not parse.
What Result is
Result is a standard library enum with two variants: Ok with the result and Err with the error. In Result<T, E>, T stands for the type of the result and E for the type of the error. parse::<i32>() returns Result<i32, ParseIntError>: on success it holds an i32, on failure a ParseIntError value, the error of parsing an integer.
Like Option, Result and its variants are available in every file without the type name: you write Ok(42) and Err(e). The two differ in meaning:
Optionsays: "there may be no value, and that is fine";Resultsays: "the operation may have failed, and here is why".
Here the courier analogy falls short. In real life a courier can bring both a parcel and a note at once. A Result always holds exactly one: either Ok or Err.
Handling it with match
You handle a Result the same way as an Option, with a match arm for each variant:
fn describe(s: &str) {
match s.parse::<i32>() {
Ok(n) => println!("number {n}"),
Err(e) => println!("error: {e}"),
}
}
fn main() {
describe("7"); // number 7
describe("x"); // error: invalid digit found in string
describe(""); // error: cannot parse integer from empty string
}- For
"7"theOk(n)arm matches: the number goes inton, and the function printsnumber 7. - For
"x"theErr(e)arm matches: the error goes intoe, and{e}prints it as text for a person. - For the empty string the cause is different, and so is the error text.
The compiler will not let you forget the Err arm: a match must cover both variants. If you do not need the cause, write Err(_).
Your own function with Result
A function that may fail says so with its return type:
fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
return Err(String::from("division by zero"));
}
Ok(a / b)
}
fn main() {
println!("{:?}", divide(10, 2)); // Ok(5)
println!("{:?}", divide(1, 0)); // Err("division by zero")
}-> Result<i32, String>promises the calling code: either a number or a string with an explanation.- When
b == 0, the function returns anErrwith a note at once. - Otherwise it returns the quotient wrapped in
Ok.
The calling code sees the possible error right in the signature and cannot miss it. You cannot add the number in a Result<i32, String> to another number: you take it out first, as with an Option.
Interviewers like to ask this: "How does Rust handle errors without exceptions?" An expected error is an ordinary Err value. The function returns it, and its type is written in the signature.
Common mistake
A function returning Result is called, and nobody looks at the result:
divide(1, 0); // ✗warning: unused `Result` that must be usedThe program builds, but with a warning. The error happened and vanished silently, like a courier's note nobody read. Rust marks Result as a value you may not throw away without a look. The fix is to handle the result with match, and if you really do not need it, discard it on purpose: let _ = divide(1, 0);.
Key points
Result<T, E>is an enum with the variantsOk(value)andErr(error); an expected error in Rust is an ordinary value.parse::<i32>()returns aResult: the whole string must be a number, otherwise you get anErr, not a panic.- You handle a
Resultwithmatch, with anOkarm and anErrarm. - An unused
Resulttriggers a warning: an error cannot get lost silently.