What the reason TypeId::of<T: 'static> constraint?

I have faced with a problem that TypeId::of has static constraint, what the reason it is there:

    ...
    pub const fn of<T: ?Sized + 'static>() -> TypeId {
        TypeId {
            t: unsafe { intrinsics::type_id::<T>() },
        }
    }
    ...

I believe that is because &'a T is a different type than &'b T even though the user might expect them to both just be &T and therefore cause confusion, because the chance of two lifetimes being exactly the same is unlikely.

I don't think lifetimes could possibly be encoded into the TypeId (how do you differentiate between iterations of the same loop, or calls to the same function?).

This means that, if non-'static types supported it, then TypeId::of(&'a T) == TypeId::of(&'b T), and anything relying on TypeId for correctness (such as Any) could then be used to transmute lifetimes.

5 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.