Bitpath

Lesson 2 · Unit 06

Your own errors and modules

An error enum, From for ?, and mod, pub and use

13 exercisesabout 3 min

What you practise

  • An error enum, From so ? converts, mod, pub and use, what the standard library gives you

Try a question from this lesson

Pick one

An error arrives as text, and the code compares text. Line 6 has a typo. What does this print?

Rust
let r: Result<i32, String> =
    Err(String::from("negative"));
match r {
    Ok(n) => println!("fine"),
    Err(e) => {
        if e == "negatve" {
            println!("no minus, please");
        } else {
            println!("unknown problem");
        }
    }
}
Hint

Compare the two pieces of text letter by letter.

The ideas

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

Concept

Errors as an enum

List the ways a function can fail as the variants of an enum, and use that enum as the error type.

Now the caller can match on the exact problem. A typo in a variant name does not compile, and a variant can carry details, such as the age that was too high.

Rust
#[derive(Debug)]
enum AgeErr { Negative, TooOld(i32) }
fn check(n: i32) -> Result<i32, AgeErr> {
    if n < 0 {
        Err(AgeErr::Negative)
    } else if n > 150 {
        Err(AgeErr::TooOld(n))
    } else {
        Ok(n)
    }
}
println!("{:?}", check(200));

Concept

From: teach ? to convert

An impl From<A> for B block holds one function, from, that turns an A into a B.

With it in place, ? converts the error for you on the way out. You write the conversion once and every ? can use it. The next unit explains the impl ... for form.

Rust
use std::num::ParseIntError;
enum AgeErr { NotNumber, Negative }
impl From<ParseIntError> for AgeErr {
    fn from(e: ParseIntError) -> AgeErr {
        AgeErr::NotNumber
    }
}
fn read(s: &str) -> Result<i32, AgeErr> {
    let n = s.parse::<i32>()?;
    Ok(n)
}

Concept

Modules

A module is a named box for related code: mod shop { ... }.

Everything inside is private unless marked pub. From outside, reach a public item by its path, shop::tax, or bring the name in once with use. Private items are helpers that the rest of the program cannot touch.

Rust
mod shop {
    pub fn tax(price: i32) -> i32 {
        round(price) / 10
    }
    fn round(price: i32) -> i32 {
        price - price % 10
    }
}
use shop::tax;

fn main() {
    println!("{}", shop::tax(57));
    println!("{}", tax(120));
}

9 more exercises in the app

  • 2× type the answer
  • 2× fill the blanks
  • 3× multiple choice
  • 1× match the pairs
  • 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