Downcast Box Dyn Error To Concrete Type
Recover the concrete type inside a Box<dyn Error> with downcast_ref so callers can branch on the original error kind.
Code
use std::error::Error;
use std::num::ParseIntError;
fn parse_level(raw: &str) -> Result<u8, Box<dyn Error>> {
Ok(raw.trim().parse::<u8>()?)
}
fn main() {
println!("ok: {:?}", parse_level(" 7 "));
// 装箱后只知道 Box<dyn Error>:先看 Display 消息
let failed = parse_level("999").unwrap_err();
println!("display: {}", failed);
// downcast_ref:把装箱错误还原成具体类型再分支处理
match failed.downcast_ref::<std::io::Error>() {
Some(e) => println!("io error: {e}"),
None => println!("not an io error"),
}
match failed.downcast_ref::<ParseIntError>() {
Some(e) => println!("parse error: {e}"),
None => println!("not a parse error"),
}
}Inside the snippet
The working surface is the functions parse_level and main — everything else is wiring.
Failure is encoded in the return type — Result leaves no room for an unhandled error. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Watch out for
- Every fallible call yields a
Resultyou must unwrap or propagate; there is no implicit throw.
Putting it to use
Entry signature: fn parse_level(raw: &str) -> Result<u8, Box<dyn Error>>
Each run prints the 6 labeled blocks ok:, display:, io error:, not an io error, parse error:, not a parse error in source order.
Treat main as the orchestrator calling parse_level in a fixed order.
Core lines
fn parse_level(raw: &str) -> Result<u8, Box<dyn Error>> {
Ok(raw.trim().parse::<u8>()?)
}
match failed.downcast_ref::<std::io::Error>() {
Some(e) => println!("io error: {e}"),
None => println!("not an io error"),
}
match failed.downcast_ref::<ParseIntError>() {
Some(e) => println!("parse error: {e}"),
None => println!("not a parse error"),
}
Interactive Tools for This Topic
Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What is the error handling style?
- Through the type system: failures are `Result` variants the caller must consume.
- What does Downcast Box Dyn Error To Concrete Type print when run?
- Running the file directly is enough — expect labeled output lines such as `ok:`, `display:`, `io error:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.