Generating unique IDs for types at compile time

前端 未结 3 1772
抹茶落季
抹茶落季 2020-12-11 10:01

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         


        
相关标签:
3条回答
  • 2020-12-11 10:39

    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 }
    
    0 讨论(0)
  • 2020-12-11 10:45

    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

    0 讨论(0)
  • 2020-12-11 10:48

    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.

    0 讨论(0)
提交回复
热议问题