Tsallaka zuwa abun ciki
Justice Tech School

The ? Operator and Custom Errors

? returns the error early from a function that returns Result. Define your own error type with an enum and implement Display and From for convenience.

Example
use std::fmt;
#[derive(Debug)]
enum AppError { Parse(std::num::ParseIntError), Negative }
impl From<std::num::ParseIntError> for AppError { fn from(e: std::num::ParseIntError) -> Self { AppError::Parse(e) } }
impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self { AppError::Parse(_) => write!(f, "not a number"), AppError::Negative => write!(f, "negative") }
    }
}
fn parse(s: &str) -> Result<i32, AppError> {
    let n: i32 = s.parse()?;
    if n < 0 { return Err(AppError::Negative); }
    Ok(n)
}
fn main() {
    for s in ["5", "-1", "x"] {
        match parse(s) { Ok(n) => println!("ok {}", n), Err(e) => println!("error: {}", e) }
    }
}

Result

ok 5
error: negative
error: not a number

Exercise

Propagate an error.

let n = s.parse::<i32>();

Quiz Test

What does ? do on an Err?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.