Bitpath

Lesson 1 · Unit 06

Result

Ok and Err, match, the ? operator, and when unwrap is fine

13 exercisesabout 3 min

What you practise

  • Ok and Err, parsing a number that might not be one, match on the result, ?, unwrap and expect and when they are fine

Try a question from this lesson

Pick one

A program has to turn the text "12a" into a number. What is the most honest thing it can do?

The ideas

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

Concept

Result: it worked, or it did not

A function that can fail returns a Result, an enum with two variants: Ok(value) when it worked and Err(error) when it did not.

parse turns text into a number. The ::<i32> part says which type you want. The text may not be a number, so the answer is a Result, and match opens it.

Rust
let text = "42";
match text.parse::<i32>() {
    Ok(n) => println!("number {}", n),
    Err(e) => println!("error: {}", e),
}

Concept

Your own function can fail too

A function that can fail should say so in its return type. Result<i32, String> means: an i32 if it works, a String describing the problem if it does not.

Inside, wrap the answer in Ok(...) or the problem in Err(...). The caller gets one value and must check which it is.

Rust
fn divide(a: i32, b: i32)
    -> Result<i32, String> {
    if b == 0 {
        Err(String::from("b is zero"))
    } else {
        Ok(a / b)
    }
}
println!("{:?}", divide(7, 2));
println!("{:?}", divide(7, 0));

Concept

? passes the error up

Often a function cannot fix an error. It should hand it to its caller. The ? operator does exactly that.

Placed after a Result, ? means: if this is Ok, give me the value inside and carry on. If it is Err, return that error from this function right now.

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"));

9 more exercises in the app

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

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