Movatterモバイル変換


[0]ホーム

URL:


TypeId

std::any

StructTypeId 

1.0.0 ·Source
pub struct TypeId {/* private fields */ }
Expand description

ATypeId represents a globally unique identifier for a type.

EachTypeId is an opaque object which does not allow inspection of what’sinside but does allow basic operations such as cloning, comparison,printing, and showing.

ATypeId is currently only available for types which ascribe to'static,but this limitation may be removed in the future.

WhileTypeId implementsHash,PartialOrd, andOrd, it is worthnoting that the hashes and ordering will vary between Rust releases. Bewareof relying on them inside of your code!

§Layout

Like otherRust-representation types,TypeId’s size and layout are unstable.In particular, this means that you cannot rely on the size and layout ofTypeId remaining thesame between Rust releases; they are subject to change without prior notice between Rustreleases.

§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 forfor<'any> fn(&'any str), andfn(&'static str), are two distinct, static types, and yet,fn(&str) is a subtype offn(&'static str), since any value of typefn(&str) can be used where a value of typefn(&'static str) is needed.

This means that abstractions aroundTypeId, despite its'static bound on arguments, still need to worry about unnecessaryand improper variance: it is advisable to strive for invariancefirst. The usability impact will be negligible, while the reductionin the risk of unsoundness will be most welcome.

§Examples

SupposeSubType is a subtype ofSuperType, that is,a value of typeSubType can be used wherevera value of typeSuperType is expected.Suppose also thatCoVar<T> is a generic type, which is covariant overT(like many other types, includingPhantomData<T> andVec<T>).

Then, by covariance,CoVar<SubType> is a subtype ofCoVar<SuperType>,that is, a value of typeCoVar<SubType> can be used wherevera value of typeCoVar<SuperType> is expected.

Then ifCoVar<SuperType> relies onTypeId::of::<SuperType>() to uphold any invariants,those invariants may be broken because a value of typeCoVar<SuperType> can be createdwithout going through any of its methods, like so:

typeSubType =fn(&());typeSuperType =fn(&'static());typeCoVar<T> = Vec<T>;// imagine something more complicatedletsub: CoVar<SubType> = CoVar::new();// we have a `CoVar<SuperType>` instance without// *ever* having called `CoVar::<SuperType>::new()`!letfake_super: CoVar<SuperType> = sub;

The following is an example program that tries to useTypeId::of toimplement a generic typeUnique<T> that guarantees unique instances for eachUnique<T>,that is, and for each typeT there can be at most one value of typeUnique<T> at any time.

modunique {usestd::any::TypeId;usestd::collections::BTreeSet;usestd::marker::PhantomData;usestd::sync::Mutex;staticID_SET: Mutex<BTreeSet<TypeId>> = Mutex::new(BTreeSet::new());// TypeId has only covariant uses, which makes Unique covariant over TypeAsId 🚨#[derive(Debug, PartialEq)]pub structUnique<TypeAsId:'static>(// private field prevents creation without `new` outside this modulePhantomData<TypeAsId>,    );impl<TypeAsId:'static> Unique<TypeAsId> {pub fnnew() ->Option<Self> {letmutset = ID_SET.lock().unwrap();            (set.insert(TypeId::of::<TypeAsId>())).then(||Self(PhantomData))        }    }impl<TypeAsId:'static> DropforUnique<TypeAsId> {fndrop(&mutself) {letmutset = ID_SET.lock().unwrap();            (!set.remove(&TypeId::of::<TypeAsId>())).then(||panic!("duplicity detected"));        }    }}useunique::Unique;// `OtherRing` is a subtype of `TheOneRing`. Both are 'static, and thus have a TypeId.typeTheOneRing =fn(&'static());typeOtherRing =fn(&());fnmain() {letthe_one_ring: Unique<TheOneRing> = Unique::new().unwrap();assert_eq!(Unique::<TheOneRing>::new(),None);letother_ring: Unique<OtherRing> = Unique::new().unwrap();// Use that `Unique<OtherRing>` is a subtype of `Unique<TheOneRing>` 🚨letfake_one_ring: Unique<TheOneRing> = other_ring;assert_eq!(fake_one_ring, the_one_ring);    std::mem::forget(fake_one_ring);}

Implementations§

Source§

implTypeId

1.0.0 (const: 1.91.0) ·Source

pub const fnof<T>() ->TypeId
where T: 'static + ?Sized,

Returns theTypeId of the generic type parameter.

§Examples
usestd::any::{Any, TypeId};fnis_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 (const:unstable) ·Source§

implClone forTypeId

Source§

fnclone(&self) ->TypeId

Returns a duplicate of the value.Read more
1.0.0 ·Source§

fnclone_from(&mut self, source: &Self)

Performs copy-assignment fromsource.Read more
1.0.0 ·Source§

implDebug forTypeId

Source§

fnfmt(&self, f: &mutFormatter<'_>) ->Result<(),Error>

Formats the value using the given formatter.Read more
1.0.0 ·Source§

implHash forTypeId

Source§

fnhash<H>(&self, state:&mut H)
where H:Hasher,

Feeds this value into the givenHasher.Read more
1.3.0 ·Source§

fnhash_slice<H>(data: &[Self], state:&mut H)
where H:Hasher, Self:Sized,

Feeds a slice of this type into the givenHasher.Read more
1.0.0 ·Source§

implOrd forTypeId

Source§

fncmp(&self, other: &TypeId) ->Ordering

This method returns anOrdering betweenself andother.Read more
1.21.0 ·Source§

fnmax(self, other: Self) -> Self
where Self:Sized,

Compares and returns the maximum of two values.Read more
1.21.0 ·Source§

fnmin(self, other: Self) -> Self
where Self:Sized,

Compares and returns the minimum of two values.Read more
1.50.0 ·Source§

fnclamp(self, min: Self, max: Self) -> Self
where Self:Sized,

Restrict a value to a certain interval.Read more
1.0.0 (const:unstable) ·Source§

implPartialEq forTypeId

Source§

fneq(&self, other: &TypeId) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

Tests for!=. The default implementation is almost always sufficient,and should not be overridden without very good reason.
1.0.0 ·Source§

implPartialOrd forTypeId

Source§

fnpartial_cmp(&self, other: &TypeId) ->Option<Ordering>

This method returns an ordering betweenself andother values if one exists.Read more
1.0.0 ·Source§

fnlt(&self, other:&Rhs) ->bool

Tests less than (forself andother) and is used by the< operator.Read more
1.0.0 ·Source§

fnle(&self, other:&Rhs) ->bool

Tests less than or equal to (forself andother) and is used by the<= operator.Read more
1.0.0 ·Source§

fngt(&self, other:&Rhs) ->bool

Tests greater than (forself andother) and is used by the>operator.Read more
1.0.0 ·Source§

fnge(&self, other:&Rhs) ->bool

Tests greater than or equal to (forself andother) and is used bythe>= operator.Read more
1.0.0 ·Source§

implCopy forTypeId

1.0.0 (const:unstable) ·Source§

implEq forTypeId

1.0.0 ·Source§

implSend forTypeId

1.0.0 ·Source§

implSync forTypeId

Auto Trait Implementations§

§

implFreeze forTypeId

§

implRefUnwindSafe forTypeId

§

implUnpin forTypeId

§

implUnwindSafe forTypeId

Blanket Implementations§

Source§

impl<T>Any for T
where T: 'static + ?Sized,

Source§

fntype_id(&self) ->TypeId

Gets theTypeId ofself.Read more
Source§

impl<T>Borrow<T> for T
where T: ?Sized,

Source§

fnborrow(&self) ->&T

Immutably borrows from an owned value.Read more
Source§

impl<T>BorrowMut<T> for T
where T: ?Sized,

Source§

fnborrow_mut(&mut self) ->&mut T

Mutably borrows from an owned value.Read more
Source§

impl<T>CloneToUninit for T
where T:Clone,

Source§

unsafe fnclone_to_uninit(&self, dest:*mutu8)

🔬This is a nightly-only experimental API. (clone_to_uninit #126799)
Performs copy-assignment fromself todest.Read more
Source§

impl<T>From<T> for T

Source§

fnfrom(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U>Into<U> for T
where U:From<T>,

Source§

fninto(self) -> U

CallsU::from(self).

That is, this conversion is whatever the implementation ofFrom<T> for U chooses to do.

Source§

impl<T>ToOwned for T
where T:Clone,

Source§

typeOwned = T

The resulting type after obtaining ownership.
Source§

fnto_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning.Read more
Source§

fnclone_into(&self, target:&mut T)

Uses borrowed data to replace owned data, usually by cloning.Read more
Source§

impl<T, U>TryFrom<U> for T
where U:Into<T>,

Source§

typeError =Infallible

The type returned in the event of a conversion error.
Source§

fntry_from(value: U) ->Result<T, <T asTryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U>TryInto<U> for T
where U:TryFrom<T>,

Source§

typeError = <U asTryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fntry_into(self) ->Result<U, <U asTryFrom<T>>::Error>

Performs the conversion.

[8]ページ先頭

©2009-2026 Movatter.jp