Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...