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

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - Generating unique IDs for types at compile time

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...