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
Box<dyn Error>erases the concrete error type.?boxes anything implementingErrorfor you.- It trades matching on variants for not declaring them.
Keywords and builtins used here
BoxErrOkResultdynfnfori32inletmainmatchparse_pairstruse
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.
Step 4 of 5 in Your own error types, step 11 of 15 in Error handling.