Skip to content
Theory · Errors · lesson 2 of 8

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:

Rust
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:

  1. "42".parse::<i32>() reads the string as a number. The angle brackets after :: hold the type to turn the text into, here i32.
  2. "42a".parse::<i32>() compiles too, and the program does not crash: the failure comes back as a value.
  3. {:?} prints the first value as Ok(42): the courier with the parcel.
  4. 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:

  • Option says: "there may be no value, and that is fine";
  • Result says: "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:

Rust
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
}
  1. For "7" the Ok(n) arm matches: the number goes into n, and the function prints number 7.
  2. For "x" the Err(e) arm matches: the error goes into e, and {e} prints it as text for a person.
  3. 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:

Rust
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")
}
  1. -> Result<i32, String> promises the calling code: either a number or a string with an explanation.
  2. When b == 0, the function returns an Err with a note at once.
  3. 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:

Rust
divide(1, 0); // ✗
TEXT
warning: unused `Result` that must be used

The 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 variants Ok(value) and Err(error); an expected error in Rust is an ordinary value.
  • parse::<i32>() returns a Result: the whole string must be a number, otherwise you get an Err, not a panic.
  • You handle a Result with match, with an Ok arm and an Err arm.
  • An unused Result triggers a warning: an error cannot get lost silently.