Bitpath

Boss lesson · Unit 02

Errors as values

Result, the ? operator and honest unwraps

13 exercisesabout 3 min

What you practise

  • Result, the ? operator, turning one error into another, unwrap and expect and when they are honest, panic!

Try a question from this lesson

Pick one

A function turns text into a number, and the text may be "abc". What should it return so that no caller can forget the failure?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Result

Rust has no exceptions. A function that can fail returns Result<T, E>, an enum with two variants: Ok(value) or Err(error).

The failure is part of the return type, so it shows in the signature, and the value inside cannot be reached without deciding what happens in the Err case.

Rust
let a = "42".parse::<i32>();
let b = "x".parse::<i32>();
println!("{:?}", a);
println!("{}", b.is_err());

Concept

The ? operator

Writing a match for every call that can fail gets long. ? after a Result does it in one character: on Ok it hands you the value, and on Err it returns that error from the current function at once.

It only works inside a function that itself returns a Result (or an Option).

Rust
use std::num::ParseIntError;
fn add(a: &str, b: &str)
    -> Result<i32, ParseIntError> {
    let x = a.parse::<i32>()?;
    let y = b.parse::<i32>()?;
    Ok(x + y)
}
println!("{:?}", add("2", "3"));

Concept

Turning one error into another

A function that can fail in several ways defines its own error type, usually an enum.

ok_or(e) turns an Option into a Result with e as the error. map_err(f) replaces the error inside a Result. |_| Bad::NotNum is a closure: a small inline function, here one that ignores its argument.

Rust
#[derive(Debug)]
enum Bad { Empty, NotNum }
let a: Result<char, Bad> =
    "".chars().next().ok_or(Bad::Empty);
let b: Result<i32, Bad> =
    "x".parse().map_err(|_| Bad::NotNum);
println!("{:?} {:?}", a, b);

9 more exercises in the app

  • 4× type the answer
  • 1× true or false
  • 1× fill the blanks
  • 2× multiple choice
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy