Expand description
A library providing direct casting among trait objects implemented by a type.
In Rust, an object of a sub-trait of Any
can be downcast to a concrete type
at runtime if the type is known. But no direct casting between two trait objects
(i.e. without involving the concrete type of the backing value) is possible
(even no coercion from a trait object to that of its super-trait yet).
With this crate, any trait object with CastFrom
as its super-trait can be cast directly
to another trait object implemented by the underlying type if the target traits are
registered beforehand with the macros provided by this crate.
§Usage
use intertrait::*;
use intertrait::cast::*;
struct Data;
trait Source: CastFrom {}
trait Greet {
fn greet(&self);
}
#[cast_to]
impl Greet for Data {
fn greet(&self) {
println!("Hello");
}
}
impl Source for Data {}
let data = Data;
let source: &dyn Source = &data;
let greet = source.cast::<dyn Greet>();
greet.unwrap().greet();
Target traits must be explicitly designated beforehand. There are three ways to do it:
#[cast_to]
toimpl
item#[cast_to(Trait)]
to type definitioncastable_to!(Type => Trait1, Trait2)
If the underlying type involved is Sync + Send
and you want to use it with Arc
,
use CastFromSync
in place of CastFrom
and add [sync]
flag before the list
of traits in the macros. Refer to the documents for each of macros for details.
For casting, refer to traits defined in cast
module.
Modules§
- cast
cast
module contains traits to providecast
method for various references and smart pointers.
Macros§
- castable_
to - Declares target traits for casting implemented by a type.
Traits§
- Cast
From CastFrom
must be extended by a trait that wants to allow for casting into another trait.- Cast
From Sync CastFromSync
must be extended by a trait that isAny + Sync + Send + 'static
and wants to allow for casting into another trait behind references and smart pointers especially includingArc
.
Attribute Macros§
- cast_to
- Attached on an
impl
item or type definition, registers traits as targets for casting.