[][src]Crate intertrait

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:

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 provide cast method for various references and smart pointers.

Macros

castable_to

Declares 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.

CastFromSync

CastFromSync must be extended by a trait that is Any + Sync + Send + 'static and wants to allow for casting into another trait behind references and smart pointers especially including Arc.

Attribute Macros

cast_to

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