Macro dyn_dyn_cast

Source
dyn_dyn_cast!() { /* proc-macro */ }
Expand description

Performs a dynamic downcast of a reference to a trait object where the trait was declared with #[dyn_dyn_base].

This macro allows for trying to cast such a reference to a reference to another trait object, returning an Option containing the reference to the downcast trait object if the object in question implements that trait.

This macro accepts the following types for a given base trait B, with the first matching set of conditions determining how the dereference will occur:

  • A (mutable) reference to a type that implements B, returning a (mutable) reference referring to the same object as the original reference
  • A (mutable) reference to a pointer type that implements DynDyn<B>, returning a (mutable) reference referring to the pointee of that pointer
  • A (mutable) reference to a pointer type that implements Deref with a target that implements B, returning a (mutable) reference referring to the pointee of that pointer

ยงExamples

#[dyn_dyn_base]
trait Base {}
trait Trait {}

struct Struct;

#[dyn_dyn_impl(Trait)]
impl Base for Struct {}
impl Trait for Struct {}

fn downcast(r: &dyn Base) -> Result<&dyn Trait, &dyn Base> {
    dyn_dyn_cast!(Base => Trait, r)
}

fn downcast_mut(r: &mut dyn Base) -> Result<&mut dyn Trait, &mut dyn Base> {
    dyn_dyn_cast!(mut Base => Trait, r)
}

fn downcast_box(r: Box<dyn Base>) -> Result<Box<dyn Trait>, Box<dyn Base>> {
    dyn_dyn_cast!(move Base => Trait, r)
}

fn main() {
    let mut s = Struct;

    assert!(downcast(&s).is_ok());
    assert!(downcast_mut(&mut s).is_ok());
    assert!(downcast_box(Box::new(s)).is_ok());
}