[][src]Crate intertrait

A library providing direct casting among trait objects implemented by a type.

In Rust, an object of a sub-trait of std::any::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) are 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::*;

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 {}

fn main() {
    let data = Data;
    let source: &dyn Source = &data;
    let greet = source.ref_to::<dyn Greet>();
    greet.unwrap().greet();
}

Target traits must be explicitly designated beforehand. There are three ways to do it:

Refer to the documents for each of macros for details.

For casting, refer to CastTo.

Macros

castable_to

Declare target traits for casting implemented by a type.

Traits

CastFrom

CastFrom must be extended by a trait that wants to allow for casting into another trait.

CastTo

A trait that is blanket-implemented for traits extending Any to allow for casting to another trait.

Attribute Macros

cast_to

Attached on an impl item or type definition, registers traits as targets for casting.