#dyn #traits #cast #derive

as_base

Cast trait objects to some base class

4 releases

0.1.3 Sep 1, 2023
0.1.2 Aug 31, 2023
0.1.1 Aug 30, 2023
0.1.0 Aug 29, 2023

#2272 in Rust patterns

MIT/Apache

5KB
50 lines

as_base

This crate allows directly accessing fields within a trait object similar to C++ public base classes. No virtual dispatch is involved, the base object always begins at the same address as the enclosing object.

use as_base::*;

struct BaseType {
    x: u64,
}

trait MyTrait: AsBase<BaseType> {}

#[derive(AsBase)]
#[repr(C)]
struct Implementor {
    pub base: BaseType,
}

impl MyTrait for Implementor {}

fn main() {
    let x = Implementor {
        base: BaseType { x: 42 },
    };
    let dyn_reference = &x as &dyn MyTrait;
    assert_eq!(dyn_reference.as_base().x, 42)
}

Dependencies

~3MB
~55K SLoC