std-method

dyn Error::downcast_ref

Inspect a dynamically erased error for a known concrete type. A mismatch returns None. Prefer typed errors for routine business decisions rather than scattering downcasts across callers. Expected stdout (not executed): true Common mistake: Assuming every wrapped cause is the outer object type.

Formal Syntax & Structure

rust syntaxrust
fn downcast_ref<T: Error + 'static>(&self) -> Option<&T>

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 main() {    let e: Box<dyn Error> = Box::new(QuantityError);    println!("{}", e.downcast_ref::<QuantityError>().is_some());}
Rust Reference