Box<dyn Error>
RustERRORNotableError Handling
Boxed dynamic error
Quick Answer
Use Box<dyn Error> for simple programs; prefer typed errors or anyhow in libraries/larger apps.
What this means
A heap-allocated trait object wrapping any type that implements std::error::Error. Commonly used as a catch-all return type for functions that can fail in multiple ways.
Why it happens
- 1fn main() returns Result<(), Box<dyn Error>>
- 2Multiple distinct error types must be unified without a custom enum
Fix
Return Box<dyn Error> from main
Return Box<dyn Error> from main
use std::fs;
use std::num::ParseIntError;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let s = fs::read_to_string("num.txt")?;
let n: i32 = s.trim().parse()?;
println!("number: {}", n);
Ok(())
}Why this works
? automatically converts any Error into Box<dyn Error> via the From impl.
Code examples
Type aliasrust
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
Sources
Official documentation ↗
Rust std::error
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev