error-concept
Box<dyn Error> — heterogeneous failures
Boxing provides a common owned error representation for differing concrete error types. Useful at an application boundary; a typed enum is often preferable when callers need structured recovery. Add Send + Sync bounds only when required. Expected stdout (not executed): quantity must be positive true Common mistake: Assuming the boxed trait object is automatically Send and Sync.
Formal Syntax & Structure
rust syntaxrust
fn run() -> Result<T, Box<dyn std::error::Error>>Working Example
Example Snippetrust
use std::{error::Error, fmt};#[derive(Debug)]struct QuantityError;impl fmt::Display for QuantityError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "quantity must be positive") }}impl Error for QuantityError {}fn run(s: &str) -> Result<u32, Box<dyn Error>> { let n: u32 = s.parse()?; if n == 0 { return Err(QuantityError.into()); } Ok(n)}fn main() { println!("{}", run("0").unwrap_err()); println!("{}", run("oops").is_err());}