[−][src]Attribute Macro cast_trait_object::dyn_cast
#[dyn_cast]
This is supported on crate feature
proc-macros
only.Allow attempting to cast a trait object to another trait object. This can be
used on traits or on types. For types you need to specify the path to the
"source" trait inside the parenthesis after the macro name like so:
#[dyn_cast(SourceTrait => TargetTrait)]
, while for traits you only need to
specify the target trait: #[dyn_cast(TargetTrait)]
.
Examples
use cast_trait_object::*; #[dyn_cast(Sub)] trait Super {} trait Sub: Super {} #[dyn_cast(Super => Sub)] struct Foo; impl Super for Foo {} impl Sub for Foo {} // We can now attempt casting between trait objects: let foo: &dyn Super = &Foo; let foo: &dyn Sub = foo.dyn_cast().ok().unwrap();
The macro can also be applied to a trait implementation (impl Trait for Type
)
instead of directly on a type:
#[dyn_cast(Sub)] impl Super for Foo {}