Traitcast
Casting from Any
In the standard library, the std::any::Any trait comes with downcast methods
which let you cast from an Any trait object to a concrete type.
let x: i32 = 7;
let y: &dyn Any = &x;
// Cast to i32 succeeds because x: i32
assert_eq!;
// Cast to f32 fails
assert_eq!;
However, it is not possible to downcast to a trait object.
trait Foo {
fn foo(&self) -> i32;
}
struct A {
x: i32
}
impl Foo for A {
fn foo(&self) -> i32 {
self.x
}
}
let x = A { x: 7 };
let y: &dyn std::any::Any = &x;
// This cast is not possible, because it is only possible to cast to types that
// are Sized. Among other things, this precludes trait objects.
let z: Option<&dyn Foo> = y.downcast_ref();
Traitcast
This library provides a way of casting between different trait objects.
use ;
// Extending `TraitcastFrom` is optional. This allows `Foo` objects themselves
// to be cast to other trait objects. If you do not extend `TraitcastFrom`,
// then Foo may only be cast into, not out of.
// Invoking `traitcast_to_trait!` implements TraitcastTo for this Foo, allowing
// other trait objects to be cast into Foo trait objects.
traitcast_to_trait!;
traitcast_to_trait!;
// No implementation of TraitcastFrom is necessary, because it is covered by
// the blanket impl for any sized type with a static lifetime.
// Register the traits.
// For each struct that implements each trait, register the implementation.
traitcast_to_impl!;
traitcast_to_impl!;