Struct TypeId
pub struct TypeId { pub(crate) data: [*const (); 2] }
A TypeId represents a globally unique identifier for a type.
Each TypeId is an opaque object which does not allow inspection of what's
inside but does allow basic operations such as cloning, comparison,
printing, and showing.
A TypeId is currently only available for types which ascribe to 'static,
but this limitation may be removed in the future.
While TypeId implements Hash, PartialOrd, and Ord, it is worth
noting that the hashes and ordering will vary between Rust releases. Beware
of relying on them inside of your code!
Layout
Like other Rust-representation types, TypeId's size and layout are unstable.
In particular, this means that you cannot rely on the size and layout of TypeId remaining the
same between Rust releases; they are subject to change without prior notice between Rust
releases.
Danger of Improper Variance
You might think that subtyping is impossible between two static types,
but this is false; there exists a static type with a static subtype.
To wit, fn(&str), which is short for for<'any> fn(&'any str), and
fn(&'static str), are two distinct, static types, and yet,
fn(&str) is a subtype of fn(&'static str), since any value of type
fn(&str) can be used where a value of type fn(&'static str) is needed.
This means that abstractions around TypeId, despite its
'static bound on arguments, still need to worry about unnecessary
and improper variance: it is advisable to strive for invariance
first. The usability impact will be negligible, while the reduction
in the risk of unsoundness will be most welcome.
Examples
Suppose SubType is a subtype of SuperType, that is,
a value of type SubType can be used wherever
a value of type SuperType is expected.
Suppose also that CoVar<T> is a generic type, which is covariant over T
(like many other types, including PhantomData<T> and Vec<T>).
Then, by covariance, CoVar<SubType> is a subtype of CoVar<SuperType>,
that is, a value of type CoVar<SubType> can be used wherever
a value of type CoVar<SuperType> is expected.
Then if CoVar<SuperType> relies on TypeId::of::<SuperType>() to uphold any invariants,
those invariants may be broken because a value of type CoVar<SuperType> can be created
without going through any of its methods, like so:
type SubType = fn;
type SuperType = fn;
type CoVar<T> = ; // imagine something more complicated
let sub: = new;
// we have a `CoVar<SuperType>` instance without
// *ever* having called `CoVar::<SuperType>::new()`!
let fake_super: = sub;
The following is an example program that tries to use TypeId::of to
implement a generic type Unique<T> that guarantees unique instances for each Unique<T>,
that is, for each type T there can be at most one value of type Unique<T> at any time.
use Unique;
// `OtherRing` is a subtype of `TheOneRing`. Both are 'static, and thus have a TypeId.
type TheOneRing = fn;
type OtherRing = fn;
Fields
data: [*const (); 2]This needs to be an array of pointers, since there is provenance in the first array field. This provenance knows exactly which type the TypeId actually is, allowing CTFE and miri to operate based off it. At runtime all the pointers in the array contain bits of the hash, making the entire
TypeIdactually just be au128hash of the type.
Implementations
impl TypeId
const fn is_signed(self) -> boolReturns
trueif the type represented by thisTypeIdis an signed integer.For everything else this returns false.
Examples
use TypeId; assert_eq!; assert_eq!; assert_eq!;const fn element_ty(self) -> Option<TypeId>When called on a
TypeIdrepresenting an array or slice this returns the type of each element otherwise this returnsNone.Examples
use TypeId; assert_eq!; assert_eq!; // not an array or sliceconst fn array_len(self) -> usizeWhen called on a
TypeIdrepresenting an array this returns the length of the array in all other cases this returns zero.Examples
use TypeId; assert_eq!; assert_eq!; // not an arrayconst fn size(self) -> Option<usize>Returns the size of the type represented by this
TypeId.Noneif it is unsized.Examples
use TypeId; assert_eq!; assert_eq!;const fn variants(self) -> usizeReturns the number of variants of the type represented by this
TypeId.For enums, this is the number of variants. For structs and unions, this is always 1.
use TypeId; assert_eq!; ; assert_eq!; assert_eq!; assert_eq!;const fn variant(self, variant_index: usize) -> VariantIdReturns the variant representing type at the given index of the type represented by this
TypeId. Use it to get the name of an enum variant or check whether it is non_exhaustive.use TypeId; assert_eq!; assert_eq!; assert_eq!; assert_eq!;The variant index refer to the source order index of a variant in a type.
Variant indexes are always
0..variant_count, regardless of any custom discriminants that may have been defined.Calling variant on the TypeId for a struct will be treated as a compile-time error. The same is true for out-of-bounds indexing on an enum.
# #![feature(type_info)] # use std::any::TypeId; # # struct Point { # x: u32, # y: u32, # } # enum Enum { # Unit, # Tuple(u32, u64), # Struct { x: u32, y: u32, z: String }, # } const { _ = TypeId::of::<Point>().variant(0); // error: cannot get the variant of a struct _ = TypeId::of::<Enum>().variant(10); // error: indexing out of bounds: the len is 3 but the index is 10 }const fn fields(self, variant_index: usize) -> usizeReturns the number of fields at the given
variant_indexof the type represented by thisTypeId.use TypeId; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;The variant index refers to the source order index of a variant in a type.
For enums, these are always
0..variant_count, regardless of any custom discriminants that may have been defined.structs,tuples, andunionss are considered to have a single variant with variant index zero.Out-of-bounds indexing will be treated as a compile-time error.
# #![feature(type_info)] # use std::any::TypeId; # # struct Point { # x: u32, # y: u32, # } # enum Enum { # Unit, # Tuple(u32, u64), # Struct { x: u32, y: u32, z: String }, # } const { _ = TypeId::of::<Point>().fields(10); // error: indexing out of bounds: the len is 2 but the index is 10 _ = TypeId::of::<Enum>().fields(10); // error: indexing out of bounds: the len is 3 but the index is 10 }const fn field(self, variant_index: usize, field_index: usize) -> FieldIdReturns the field representing type at the given index of the type represented by this
TypeId.use TypeId; assert_eq!; assert_eq!; assert_eq!; assert_eq!;The variant index and field index refer to the source order index of a variant in a type and the source order index of a field in a variant, respectively.
For enums, variant indexes are always
0..variant_count, regardless of any custom discriminants that may have been defined.structs,tuples, andunionss are considered to have a single variant with variant index zero.As for field indexes, they may not be the same as the layout order for
repr(Rust)types, but they are forrepr(C)types.Out-of-bounds indexing will be treated as a compile-time error.
# #![feature(type_info)] # use std::any::TypeId; # # struct Point { # x: u32, # y: u32, # } # enum Enum { # Unit, # Tuple(u32, u64), # Struct { x: u32, y: u32, z: String }, # } const { _ = TypeId::of::<Point>().field(0, 10); // error: indexing out of bounds: the len is 2 but the index is 10 _ = TypeId::of::<Enum>().field(2, 10); // error: indexing out of bounds: the len is 3 but the index is 10 }const fn non_exhaustive(self) -> boolReturns whether a type is marked with
#[non_exhaustive]. Returnsfalsefor everything but adts.const fn generics(self) -> &'static [Generic]Returns a list of generic parameters of the type. Returns an empty slice for everything that doesn't have generics.
const fn points_to(self) -> Option<TypeId>Given a
TypeIdthat represents a pointer this returns theTypeIdwhich that pointer points to. When called on anything else this returns None.use TypeId; assert_eq!; assert_eq!;const fn points_mutably(self) -> boolGiven a
TypeIdthat represents a pointer returns whether that pointer is mutable. When called on anything else this returnsfalse.use TypeId; assert!; assert!; assert!; assert!;const fn function_ptr(self) -> Option<FnPtr>Given a
TypeIdthat represents a function pointer returns anFnPtr. When called on something else this returnsNone.use TypeId; use ; const F: FnPtr = .function_ptr .expect; assert!; assert!; assert!;# use TypeId; # use ; # const F: FnPtr = .function_ptr .expect; assert!; assert!; assert!;
impl TypeId
const fn of<T: ?Sized + 'static>() -> TypeIdReturns the
TypeIdof the generic type parameter.Examples
use ; Sized + Any> assert_eq!; assert_eq!;const fn trait_info_of<'a, T: TryAsDynCompatible<'a> + ?Sized>(self) -> Option<TraitImpl<T>>Checks if the [TypeId] implements the trait. If it does it returns [TraitImpl] which can be used to build a fat pointer. It can only be called at compile time.
selfmust be the [TypeId] of a sized type or None will be returned.Examples
use ; assert!; assert!;const fn trait_info_of_trait_type_id(self, trait_represented_by_type_id: TypeId) -> Option<TraitImpl<*const ()>>Checks if the [TypeId] implements the trait of
trait_represented_by_type_id. If it does it returns [TraitImpl] which can be used to build a fat pointer. It can only be called at compile time.selfmust be the [TypeId] of a sized type or None will be returned.Examples
use ; assert!; assert!;fn as_u128(self) -> u128
impl TypeId
const fn info(self) -> TypeCompute the type information of a concrete type. It can only be called at compile time.
Trait Implementations
impl Clone for TypeId
fn clone(&self) -> Self
impl Copy for TypeId
impl Debug for TypeId
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
impl Eq for TypeId
fn assert_fields_are_eq(&self)
impl Hash for TypeId
fn hash<H: Hasher>(&self, state: &mut H)
impl Ord for TypeId
fn cmp(&self, other: &Self) -> Ordering
impl PartialEq for TypeId
fn eq(&self, other: &Self) -> bool
impl PartialOrd for TypeId
fn partial_cmp(&self, other: &Self) -> Option<Ordering>
impl Send for TypeId
impl Sync for TypeId
impl TrivialClone for TypeId
Auto Trait Implementations
impl Freeze for TypeId
impl RefUnwindSafe for TypeId
impl Unpin for TypeId
impl UnsafeUnpin for TypeId
impl UnwindSafe for TypeId
Blanket Implementations
impl<T> Any for TypeId
where
T: 'static + ?Sized,
fn type_id(&self) -> TypeId
impl<T> Borrow<T> for TypeId
where
T: ?Sized,
fn borrow(&self) -> &T
impl<T> BorrowMut<T> for TypeId
where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
impl<T> CloneToUninit for TypeId
where
T: Clone,
unsafe fn clone_to_uninit(&self, dest: *mut u8)
impl<T> From<T> for TypeId
fn from(t: T) -> TReturns the argument unchanged.
impl<T> Printable for TypeId
where
T: Copy + Debug,
impl<T> SizeHint for TypeId
where
T: ?Sized,
fn lower_bound(&self) -> usizefn upper_bound(&self) -> Option<usize>
impl<T> SizedTypeProperties for TypeId
impl<T, U> Into<U> for TypeId
where
U: From<T>,
fn into(self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom<U> for TypeId
where
U: Into<T>,
type Error = never;fn try_from(value: U) -> Result<T, never>
impl<T, U> TryInto<U> for TypeId
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error;fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>