pub struct TypeId { /* private fields */ }
Expand description
core
Represents a globally unique identifier for a type.
Re-exported from core
::any::
.
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!
§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(&'static ());
type CoVar<T> = Vec<T>; // imagine something more complicated
let sub: CoVar<SubType> = CoVar::new();
// we have a `CoVar<SuperType>` instance without
// *ever* having called `CoVar::<SuperType>::new()`!
let fake_super: CoVar<SuperType> = 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, and for each type T
there can be at most one value of type Unique<T>
at any time.
mod unique {
use std::any::TypeId;
use std::collections::BTreeSet;
use std::marker::PhantomData;
use std::sync::Mutex;
static ID_SET: Mutex<BTreeSet<TypeId>> = Mutex::new(BTreeSet::new());
// TypeId has only covariant uses, which makes Unique covariant over TypeAsId 🚨
#[derive(Debug, PartialEq)]
pub struct Unique<TypeAsId: 'static>(
// private field prevents creation without `new` outside this module
PhantomData<TypeAsId>,
);
impl<TypeAsId: 'static> Unique<TypeAsId> {
pub fn new() -> Option<Self> {
let mut set = ID_SET.lock().unwrap();
(set.insert(TypeId::of::<TypeAsId>())).then(|| Self(PhantomData))
}
}
impl<TypeAsId: 'static> Drop for Unique<TypeAsId> {
fn drop(&mut self) {
let mut set = ID_SET.lock().unwrap();
(!set.remove(&TypeId::of::<TypeAsId>())).then(|| panic!("duplicity detected"));
}
}
}
use unique::Unique;
// `OtherRing` is a subtype of `TheOneRing`. Both are 'static, and thus have a TypeId.
type TheOneRing = fn(&'static ());
type OtherRing = fn(&());
fn main() {
let the_one_ring: Unique<TheOneRing> = Unique::new().unwrap();
assert_eq!(Unique::<TheOneRing>::new(), None);
let other_ring: Unique<OtherRing> = Unique::new().unwrap();
// Use that `Unique<OtherRing>` is a subtype of `Unique<TheOneRing>` 🚨
let fake_one_ring: Unique<TheOneRing> = other_ring;
assert_eq!(fake_one_ring, the_one_ring);
std::mem::forget(fake_one_ring);
}
Implementations§
Source§impl TypeId
impl TypeId
1.0.0 (const: unstable) · Sourcepub fn of<T>() -> TypeIdwhere
T: 'static + ?Sized,
pub fn of<T>() -> TypeIdwhere
T: 'static + ?Sized,
Returns the TypeId
of the generic type parameter.
§Examples
use std::any::{Any, TypeId};
fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
TypeId::of::<String>() == TypeId::of::<T>()
}
assert_eq!(is_string(&0), false);
assert_eq!(is_string(&"cookie monster".to_string()), true);
Trait Implementations§
1.0.0 · Source§impl Ord for TypeId
impl Ord for TypeId
1.0.0 · Source§impl PartialOrd for TypeId
impl PartialOrd for TypeId
impl Copy for TypeId
impl Eq for TypeId
Auto Trait Implementations§
impl Freeze for TypeId
impl RefUnwindSafe for TypeId
impl Send for TypeId
impl Sync for TypeId
impl Unpin for TypeId
impl UnwindSafe for TypeId
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> ByteSized for T
impl<T> ByteSized for T
Source§const BYTE_ALIGN: usize = _
const BYTE_ALIGN: usize = _
Source§fn byte_align(&self) -> usize
fn byte_align(&self) -> usize
Source§fn ptr_size_ratio(&self) -> [usize; 2]
fn ptr_size_ratio(&self) -> [usize; 2]
Source§impl<T, R> Chain<R> for Twhere
T: ?Sized,
impl<T, R> Chain<R> for Twhere
T: ?Sized,
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.Source§impl<T> ExtAny for T
impl<T> ExtAny for T
Source§fn type_hash_with<H: Hasher>(&self, hasher: H) -> u64
fn type_hash_with<H: Hasher>(&self, hasher: H) -> u64
TypeId
of Self
using a custom hasher.Source§fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
Source§impl<T> ExtMem for Twhere
T: ?Sized,
impl<T> ExtMem for Twhere
T: ?Sized,
Source§const NEEDS_DROP: bool = _
const NEEDS_DROP: bool = _
Source§fn mem_align_of<T>() -> usize
fn mem_align_of<T>() -> usize
Source§fn mem_align_of_val(&self) -> usize
fn mem_align_of_val(&self) -> usize
Source§fn mem_size_of<T>() -> usize
fn mem_size_of<T>() -> usize
Source§fn mem_size_of_val(&self) -> usize
fn mem_size_of_val(&self) -> usize
Source§fn mem_needs_drop(&self) -> bool
fn mem_needs_drop(&self) -> bool
true
if dropping values of this type matters. Read moreSource§fn mem_forget(self)where
Self: Sized,
fn mem_forget(self)where
Self: Sized,
self
without running its destructor. Read moreSource§fn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
fn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
Source§unsafe fn mem_zeroed<T>() -> T
unsafe fn mem_zeroed<T>() -> T
unsafe_layout
only.T
represented by the all-zero byte-pattern. Read moreSource§unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe_layout
only.T
represented by the all-zero byte-pattern. Read moreSource§fn mem_as_bytes(&self) -> &[u8] ⓘ
fn mem_as_bytes(&self) -> &[u8] ⓘ
unsafe_slice
only.§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> Hook for T
impl<T> Hook for T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more