rsRustPrimer
< Back to module

Error handling

The Result type

Result<T, E> is an enum with two variants: Ok(T) holds the value on success, Err(E) describes the error. Unlike unchecked Java exceptions, the error is part of the return type: you cannot overlook that a function may fail.

rust
fn parse_quantity(text: &str) -> Result<f64, String> {
match text.trim().parse::<f64>() {
Ok(q) if q > 0.0 => Ok(q),
Ok(q) => Err(format!("quantité non positive : {q}")),
Err(e) => Err(format!("'{text}' n'est pas un nombre ({e})")),
}
}
fn main() {
for input in ["1000", "-5", "abc"] {
match parse_quantity(input) {
Ok(q) => println!("ok : {q}"),
Err(message) => println!("erreur : {message}"),
}
}
}

A few methods save you from writing a match every time. unwrap_or(default) provides a fallback value. map transforms the value when it is an Ok. ok() turns a Result into an Option, dropping the error, and ok_or(error) does the reverse.

rust
fn main() {
let haircut: f64 = "abc".parse().unwrap_or(0.0);
println!("{haircut}"); // 0
let rates = vec![0.031, 0.028];
let ten_year: Result<f64, String> = rates.get(10).copied().ok_or(String::from("pas de taux 10 ans"));
println!("{ten_year:?}");
}

Your turn

Write parse_direction, which accepts "long" or "short" (ignoring case and surrounding spaces) and returns an explicit error otherwise.

src/main.rs
#[derive(Debug)]
enum Direction {
Long,
Short,
}
fn parse_direction(text: &str) -> Result<Direction, String> {
todo!()
}
fn main() {
println!("{:?}", parse_direction(" LONG ")); // Ok(Long)
println!("{:?}", parse_direction("buy")); // Err("sens inconnu : buy")
}