I want to generate a unique id for every type at compile time. Is this possible in Rust?
So far, I have the following code
//Pseudo code
struct Class
std::any::TypeId does something like that:
use std::any::TypeId;
fn main() {
let type_id = TypeId::of::<isize>();
println!("{:?}", type_id);
}
outputs:
TypeId { t: 4150853580804116396 }
This sounds like a job for the bitflags! macro:
#[macro_use] extern crate rustc_bitflags;
bitflags!(
#[derive(Debug)]
flags ComponentMask: u8 {
const Render = 0b00000001,
const Position = 0b00000010,
const Physics = 0b00000100
}
);
// the set of components owned by an entity:
let owned_components: = Render | Position;
// check whether an entity has a certain component:
if owned_components.contains(Physics) { ... }
http://doc.rust-lang.org/rustc_bitflags/macro.bitflags!.html
If you want to manage type ids manually, you can use my unique-type-id crate. It allows you to specify what ids a type has in a special file. It will generate them at compile time. Currently it can be used in this way:
use unique_type_id::UniqueTypeId;
#[derive(UniqueTypeId)]
struct Test1;
#[derive(UniqueTypeId)]
struct Test2;
assert_eq!(Test1::id().0, 1u64);
assert_eq!(Test2::id().0, 2u64);
It can both generate types using incremental number and use the id from a file.