Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating unique IDs for types at compile time

Tags:

rust

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 ClassTypeId{
    id: &'static uint
}
impl ClassTypeId{
    fn get_type<T>(&mut self) -> &'static uint {
        let _id :&'static uint = self.id + 1;
        self.id = _id;
        _id
    }
}

let c = ClassTypeId{id:0};
c.get_type::<i32>();  // returns 1
c.get_type::<f32>();  // returns 2
c.get_type::<i32>();  // returns 1
c.get_type::<uint>(); // returns 3

I stole this idea from a C++ library, which looks like this

typedef std::size_t TypeId;

        template <typename TBase>
        class ClassTypeId
        {
        public:

            template <typename T>
            static TypeId GetTypeId()
            {
                static const TypeId id = m_nextTypeId++;
                return id;
            }

        private:

            static TypeId m_nextTypeId;
        };

        template <typename TBase>
        TypeId ClassTypeId<TBase>::m_nextTypeId = 0;
    }
like image 760
Maik Klein Avatar asked Dec 01 '22 18:12

Maik Klein


1 Answers

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 }
like image 199
Paige Ruten Avatar answered Dec 15 '22 03:12

Paige Ruten