Crate any_trait

Crate any_trait 

Source
Expand description

§AnyTrait

This is a no_std crate that lets you cast from:

  • your concrete type
  • &dyn AnyTrait to:
  • the concrete type
  • any other trait implemented by your type
  • &dyn AnyTrait

If the trait implements AnyTrait, that too can be cast to:

  • the concrete type
  • any other trait implemented by your type
  • &dyn AnyTrait

This is not zero-cost, since at any cast we need to go through the list of all possible subtraits.

This will (almost) enable you to do OOP in rust, but if this is your goal we still ask you to kindly reconsider

example usage:

use any_trait::{AnySubTrait, AnyTrait, AsAnyTrait, AnyTraitCast};
trait TA {}
trait TB : AnyTrait {} // if a trait implements `AnyTrait` you can upi/downcast
#[derive(AnySubTrait)]
#[any_sub_trait(TA, TB)] // must include all traits you want to downcast to
struct Concrete {
    // whatever
}
impl TA for Concrete {}
impl TB for Concrete {}
fn test() {
    let c = Concrete{};

    let a = c.as_anytrait();

    let ta :&dyn TA = a.cast_ref::<dyn TA>().unwrap();
    let tb :&dyn TB = a.cast_ref::<dyn TB>().unwrap();

    let ta_from_tb : &dyn TA = tb.cast_ref::<dyn TA>().unwrap();

    let a2 = tb.as_anytrait();
    let c_ref : &Concrete = a2.cast_ref::<Concrete>().unwrap();
}

Modules§

anyptr
Type erasure for pointers
typeidconst
Internal implementation of a const-comparable TypeId

Traits§

AnyTrait
AnyTrait
AnyTraitCast
(Up/Down)cast to another type
AsAnyTrait
upcast from the concrete type

Derive Macros§

AnySubTrait
Add the AnyTrait implementation