Description
It's needed for things like an Any
type, or safe dynamic loading.
It basically needs to be an generic intrinsic that returns some kind of data structure that uniquely identifies the generic type it has been instantiated with. Ideally it also includes information about the crate itself and it's meta data, so that two different named and/or versioned crates with the same type result in different TypeID
s.
Currently, the static pointers to type descriptors can be kinda used for this, but there is no guarantee that a type descriptor can not be duplicated, so using them for this purpose is incorrect.
Possible usage could look like this:
fn same_types<T, U>() -> bool {
let type_id_t = intrinsics::type_id::<T>();
let type_id_u = intrinsics::type_id::<U>();
type_id_t == type_id_u
}
fn main() {
assert!(same_types::<uint, uint>());
let type_id = intrinsics::type_id::<std::util::Void>();
assert!(type_id.path().to_str() == "<6df45e453>::std::util::Void");
assert!(type_id.crate().name() == "std");
assert!(type_id.crate().version() == "1.0");
assert!(type_id.crate().hash() == "6df45e453");
}
See also https://gist.github.com/Kimundi/6802198 for some prototype implementation of a TypeID
using type descriptors.
Activity
brson commentedon Oct 25, 2013
Nominating.
std::sys
for removal, and madebegin_unwind
simpler #10120orenbenkiki commentedon Nov 2, 2013
Comparing
TypeId
for equality is great, but it would also be very nice if it were possible to access the names of the types, especially for error messages. Would it be possible forTypeId
to offer aname() -> &'static str
(or maybe~str
) method?I know unique names of types across different crates are tricky, but even if given only the unique name within the defining crate, this would be extremely useful for debugging dynamic type errors.
alexcrichton commentedon Nov 2, 2013
I don't think that the type id is the right location for the name, but there is a
name
field on theTyDesc
, and that can be called for arbitrary types. Additionally, you may also be able to use theTyVisitor
to build the name of a type.orenbenkiki commentedon Nov 2, 2013
Fair point... that said, it seems silly we have
TypeId
andTyDesc
and no relationship between them. Doesn't it make sense to unify them both (e.g., addEq
toTyDesc
)? Or, barring that, at least provide an easy way to get one from the other?alexcrichton commentedon Nov 3, 2013
That's not a bad idea unifying them. I think right now the blocker for that is that
type_id
is only defined forT: 'static
whereget_tydesc
is defined for allT
. If we can lift that restriction, I think it would be a bit easier to unify the two of them, but for the time being it may be difficult to do so.auto merge of #10182 : alexcrichton/rust/typeid-intrinsic, r=nikomats…
auto merge of #10182 : alexcrichton/rust/typeid-intrinsic, r=nikomats…