typestar

Box<dyn Error> in Rust

A boxed trait object holds any error, which suits application code and mains.

use std::error::Error;

fn parse_pair(text: &str) -> Result<(i32, i32), Box<dyn Error>> {
    let (a, b) = text.split_once(',').ok_or("expected a comma")?;
    Ok((a.trim().parse()?, b.trim().parse()?))
}

fn main() {
    println!("{:?}", parse_pair("3, 4"));
    for bad in ["3 4", "3, x"] {
        match parse_pair(bad) {
            Ok(pair) => println!("{:?}", pair),
            Err(e) => println!("{bad:?} -> {e}"),
        }
    }
}

How it works

  1. Box<dyn Error> erases the concrete error type.
  2. ? boxes anything implementing Error for you.
  3. It trades matching on variants for not declaring them.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
380
Tokens
149
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 4 of 5 in Your own error types, step 11 of 15 in Error handling.

← Previous Next →