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;
}
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With