#dyn #traits #derive #cast

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

#2288 in Rust patterns

Download history 2/week @ 2023-11-12 14/week @ 2023-11-19 15/week @ 2023-11-26 8/week @ 2023-12-03 4/week @ 2023-12-17 13/week @ 2023-12-24 1/week @ 2023-12-31 17/week @ 2024-01-28 1/week @ 2024-02-04 21/week @ 2024-02-11 134/week @ 2024-02-18

173 downloads per month

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
~57K SLoC