← Retour au cours: Rust from scratch

Result, errors and the ? operator

Vidéo bientôt disponible

Rust splits errors into two categories. Unrecoverable ones, like accessing outside an array, cause a panic (panic!) and stop the program. Recoverable ones, like a file that does not exist or a text that is not a number, are represented with the Result<T, E> type. The idea is simple and powerful: a function that can fail says so in its signature, and whoever calls it is forced by the compiler to handle the error. No hidden exceptions traveling up the stack without warning.

Result<T, E>

Result is an enum with two variants: Ok(value) when everything went fine and Err(error) when it failed. You can handle it with match like any enum. A typical case is parse, which converts text to a number and returns Result because the text might not be valid. The same shortcuts you saw on Option exist here: unwrap_or, map, and_then, is_ok, is_err. And also unwrap and expect, which panic if there is an Err; use them only in tests, quick examples or when the error is truly impossible.

rust
use std::num::ParseIntError;

fn parse_age(text: &str) -> Result<u32, ParseIntError> {
    text.trim().parse::<u32>()
}

fn main() {
    match parse_age(" 42 ") {
        Ok(age) => println!("age = {age}"),
        Err(e) => println!("invalid: {e}"),
    }
    match parse_age("forty") {
        Ok(age) => println!("age = {age}"),
        Err(e) => println!("invalid: {e}"),
    }
    println!("{}", parse_age("-5").unwrap_or(0));
    println!("{:?}", parse_age("7"));
}

The ? operator

When a function calls another that can fail and only wants "if it failed, return the error to whoever called me", writing a match each time is heavy. The ? operator sums it up: if the Result is Ok, it extracts the value and continues; if it is Err, it leaves the function immediately returning that error. It can only be used in functions whose return type is Result (or Option, with the same idea for None). Also, ? converts the error to your function's error type using the From trait, which lets you mix different error types.

rust
use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
enum InputError {
    Parse(ParseIntError),
    OutOfRange(i64),
}

impl fmt::Display for InputError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            InputError::Parse(e) => write!(f, "not a number ({e})"),
            InputError::OutOfRange(n) => write!(f, "{n} is out of range 1..=10"),
        }
    }
}

impl From<ParseIntError> for InputError {
    fn from(e: ParseIntError) -> Self {
        InputError::Parse(e)
    }
}

fn read_rating(text: &str) -> Result<i64, InputError> {
    let n: i64 = text.trim().parse()?; // ParseIntError -> InputError via From
    if !(1..=10).contains(&n) {
        return Err(InputError::OutOfRange(n));
    }
    Ok(n)
}

fn average(a: &str, b: &str) -> Result<f64, InputError> {
    let x = read_rating(a)?;
    let y = read_rating(b)?;
    Ok((x + y) as f64 / 2.0)
}

fn main() {
    for (a, b) in [("8", "9"), ("8", "abc"), ("8", "15")] {
        match average(a, b) {
            Ok(avg) => println!("average = {avg}"),
            Err(e) => println!("error: {e}"),
        }
    }
}

main can return Result

For small programs you can make main return Result<(), Box<dyn Error>>. Box<dyn Error> is an "any error" type: it accepts any type that implements the Error trait, so ? works without writing conversions. If main returns an Err, the program prints the error and exits with a non-zero exit code, which is exactly what scripts and command-line tools expect. It is a convenient solution for applications; for libraries it is better to define your own error type, as we did above.

rust
use std::error::Error;

fn double(text: &str) -> Result<i32, Box<dyn Error>> {
    let n: i32 = text.parse()?;
    if n > 1000 {
        return Err("too big".into());
    }
    Ok(n * 2)
}

fn main() -> Result<(), Box<dyn Error>> {
    println!("{}", double("21")?);
    println!("{}", double("5000")?); // returns Err: program ends with code 1
    println!("never printed");
    Ok(())
}
rust
fn parse_pair(text: &str) -> Result<(i32, i32), String> {
    let (a, b) = text.split_once(',').ok_or("missing comma".to_string())?;
    let a = a.trim().parse::<i32>().map_err(|e| e.to_string())?;
    let b = b.trim().parse::<i32>().map_err(|e| e.to_string())?;
    Ok((a, b))
}

fn main() {
    for input in ["3,4", "3-4", "3,x"] {
        println!("{:?}", parse_pair(input));
    }
}

Testez vos acquis

Question 1 sur 6

Which variants does Result<T, E> have?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →