Crates.io | multi-trait-object |
lib.rs | multi-trait-object |
version | 0.2.0 |
source | src |
created_at | 2022-03-13 14:24:57.440861 |
updated_at | 2022-03-13 19:38:29.191191 |
description | A type to store an object with all associated traits |
homepage | |
repository | https://github.com/Trivernis/multi-trait-object/tree/main |
max_upload_size | |
id | 549218 |
size | 29,774 |
This crate provides a pointer type that allows casting into all registered traits for a given type. This is done by storing the pointer to the v-table for each trait implementation on the type as well as the pointer to the data.
All unsafe parts are perfectly safe as far as my understanding goes. As this crate is still in an early stage there might be some side effects that haven't been noticed yet.
use multi_trait_object::*;
use std::fmt::Debug;
#[derive(Debug)]
struct MyStruct {
a: u64,
}
trait MyTrait {}
trait MyOtherTrait {}
impl MyTrait for MyStruct{}
impl MyOtherTrait for MyStruct {}
impl_trait_object!(MyStruct, dyn MyTrait, dyn MyOtherTrait, dyn Debug);
fn main() {
let obj = MyStruct {
a: 5
};
let mto = obj.into_multitrait();
{
let debug = mto.downcast_trait::<dyn Debug>().unwrap();
println!("{:?}", debug);
let my_trait = mto.downcast_trait::<dyn MyTrait>().unwrap();
}
let trait_box: Box<dyn MyTrait> = mto.downcast_trait_boxed::<dyn MyTrait>().unwrap();
}
Apache-2.0