Struct frame_support::dispatch::marker::PhantomData
1.0.0 · source · [−]pub struct PhantomData<T>
where
T: ?Sized;
Expand description
Zero-sized type used to mark things that “act like” they own a T
.
Adding a PhantomData<T>
field to your type tells the compiler that your
type acts as though it stores a value of type T
, even though it doesn’t
really. This information is used when computing certain safety properties.
For a more in-depth explanation of how to use PhantomData<T>
, please see
the Nomicon.
A ghastly note 👻👻👻
Though they both have scary names, PhantomData
and ‘phantom types’ are
related, but not identical. A phantom type parameter is simply a type
parameter which is never used. In Rust, this often causes the compiler to
complain, and the solution is to add a “dummy” use by way of PhantomData
.
Examples
Unused lifetime parameters
Perhaps the most common use case for PhantomData
is a struct that has an
unused lifetime parameter, typically as part of some unsafe code. For
example, here is a struct Slice
that has two pointers of type *const T
,
presumably pointing into an array somewhere:
struct Slice<'a, T> {
start: *const T,
end: *const T,
}
The intention is that the underlying data is only valid for the
lifetime 'a
, so Slice
should not outlive 'a
. However, this
intent is not expressed in the code, since there are no uses of
the lifetime 'a
and hence it is not clear what data it applies
to. We can correct this by telling the compiler to act as if the
Slice
struct contained a reference &'a T
:
use std::marker::PhantomData;
struct Slice<'a, T: 'a> {
start: *const T,
end: *const T,
phantom: PhantomData<&'a T>,
}
This also in turn requires the annotation T: 'a
, indicating
that any references in T
are valid over the lifetime 'a
.
When initializing a Slice
you simply provide the value
PhantomData
for the field phantom
:
fn borrow_vec<T>(vec: &Vec<T>) -> Slice<'_, T> {
let ptr = vec.as_ptr();
Slice {
start: ptr,
end: unsafe { ptr.add(vec.len()) },
phantom: PhantomData,
}
}
Unused type parameters
It sometimes happens that you have unused type parameters which
indicate what type of data a struct is “tied” to, even though that
data is not actually found in the struct itself. Here is an
example where this arises with FFI. The foreign interface uses
handles of type *mut ()
to refer to Rust values of different
types. We track the Rust type using a phantom type parameter on
the struct ExternalResource
which wraps a handle.
use std::marker::PhantomData;
use std::mem;
struct ExternalResource<R> {
resource_handle: *mut (),
resource_type: PhantomData<R>,
}
impl<R: ResType> ExternalResource<R> {
fn new() -> Self {
let size_of_res = mem::size_of::<R>();
Self {
resource_handle: foreign_lib::new(size_of_res),
resource_type: PhantomData,
}
}
fn do_stuff(&self, param: ParamType) {
let foreign_params = convert_params(param);
foreign_lib::do_stuff(self.resource_handle, foreign_params);
}
}
Ownership and the drop check
Adding a field of type PhantomData<T>
indicates that your
type owns data of type T
. This in turn implies that when your
type is dropped, it may drop one or more instances of the type
T
. This has bearing on the Rust compiler’s drop check
analysis.
If your struct does not in fact own the data of type T
, it is
better to use a reference type, like PhantomData<&'a T>
(ideally) or PhantomData<*const T>
(if no lifetime applies), so
as not to indicate ownership.
Trait Implementations
sourceimpl<T> Clone for PhantomData<T> where
T: ?Sized,
impl<T> Clone for PhantomData<T> where
T: ?Sized,
sourcepub fn clone(&self) -> PhantomData<T>
pub fn clone(&self) -> PhantomData<T>
Returns a copy of the value. Read more
sourcefn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source
. Read more
sourceimpl<T> Debug for PhantomData<T> where
T: ?Sized,
impl<T> Debug for PhantomData<T> where
T: ?Sized,
sourceimpl<T> Decode for PhantomData<T>
impl<T> Decode for PhantomData<T>
sourcepub fn decode<I>(_input: &mut I) -> Result<PhantomData<T>, Error> where
I: Input,
pub fn decode<I>(_input: &mut I) -> Result<PhantomData<T>, Error> where
I: Input,
Attempt to deserialise the value from input.
sourcefn skip<I>(input: &mut I) -> Result<(), Error> where
I: Input,
fn skip<I>(input: &mut I) -> Result<(), Error> where
I: Input,
Attempt to skip the encoded value from input. Read more
sourcefn encoded_fixed_size() -> Option<usize>
fn encoded_fixed_size() -> Option<usize>
Returns the fixed encoded size of the type. Read more
const: unstable · sourceimpl<T> Default for PhantomData<T> where
T: ?Sized,
impl<T> Default for PhantomData<T> where
T: ?Sized,
const: unstable · sourcepub fn default() -> PhantomData<T>
pub fn default() -> PhantomData<T>
Returns the “default value” for a type. Read more
sourceimpl<'de, T> Deserialize<'de> for PhantomData<T> where
T: ?Sized,
impl<'de, T> Deserialize<'de> for PhantomData<T> where
T: ?Sized,
sourcepub fn deserialize<D>(
deserializer: D
) -> Result<PhantomData<T>, <D as Deserializer<'de>>::Error> where
D: Deserializer<'de>,
pub fn deserialize<D>(
deserializer: D
) -> Result<PhantomData<T>, <D as Deserializer<'de>>::Error> where
D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
sourceimpl<'de, T> DeserializeSeed<'de> for PhantomData<T> where
T: Deserialize<'de>,
impl<'de, T> DeserializeSeed<'de> for PhantomData<T> where
T: Deserialize<'de>,
type Value = T
type Value = T
The type produced by using this seed.
sourcepub fn deserialize<D>(
self,
deserializer: D
) -> Result<T, <D as Deserializer<'de>>::Error> where
D: Deserializer<'de>,
pub fn deserialize<D>(
self,
deserializer: D
) -> Result<T, <D as Deserializer<'de>>::Error> where
D: Deserializer<'de>,
Equivalent to the more common Deserialize::deserialize
method, except
with some initial piece of data (the seed) passed in. Read more
sourceimpl<T> Encode for PhantomData<T>
impl<T> Encode for PhantomData<T>
sourcepub fn encode_to<W>(&self, _dest: &mut W) where
W: Output + ?Sized,
pub fn encode_to<W>(&self, _dest: &mut W) where
W: Output + ?Sized,
Convert self to a slice and append it to the destination.
sourcefn size_hint(&self) -> usize
fn size_hint(&self) -> usize
If possible give a hint of expected size of the encoding. Read more
sourcefn encode(&self) -> Vec<u8, Global>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
fn encode(&self) -> Vec<u8, Global>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
A: Allocator,
Convert self to an owned vector.
sourcefn using_encoded<R, F>(&self, f: F) -> R where
F: FnOnce(&[u8]) -> R,
fn using_encoded<R, F>(&self, f: F) -> R where
F: FnOnce(&[u8]) -> R,
Convert self to a slice and then invoke the given closure with it.
sourcefn encoded_size(&self) -> usize
fn encoded_size(&self) -> usize
Calculates the encoded size. Read more
sourceimpl<T> Hash for PhantomData<T> where
T: ?Sized,
impl<T> Hash for PhantomData<T> where
T: ?Sized,
sourceimpl<T> MallocSizeOf for PhantomData<T>
impl<T> MallocSizeOf for PhantomData<T>
sourcepub fn size_of(&self, &mut MallocSizeOfOps) -> usize
pub fn size_of(&self, &mut MallocSizeOfOps) -> usize
Measure the heap usage of all descendant heap-allocated structures, but
not the space taken up by the value itself.
If T::size_of
is a constant, consider implementing constant_size
as well. Read more
sourcepub fn constant_size() -> Option<usize>
pub fn constant_size() -> Option<usize>
Used to optimize MallocSizeOf
implementation for collections
like Vec
and HashMap
to avoid iterating over them unnecessarily.
The Self: Sized
bound is for object safety. Read more
sourceimpl<T> MaxEncodedLen for PhantomData<T>
impl<T> MaxEncodedLen for PhantomData<T>
sourcepub fn max_encoded_len() -> usize
pub fn max_encoded_len() -> usize
Upper bound, in bytes, of the maximum encoded size of this item.
sourceimpl<T> Ord for PhantomData<T> where
T: ?Sized,
impl<T> Ord for PhantomData<T> where
T: ?Sized,
sourceimpl<T> PartialEq<PhantomData<T>> for PhantomData<T> where
T: ?Sized,
impl<T> PartialEq<PhantomData<T>> for PhantomData<T> where
T: ?Sized,
sourceimpl<T> PartialOrd<PhantomData<T>> for PhantomData<T> where
T: ?Sized,
impl<T> PartialOrd<PhantomData<T>> for PhantomData<T> where
T: ?Sized,
sourcepub fn partial_cmp(&self, _other: &PhantomData<T>) -> Option<Ordering>
pub fn partial_cmp(&self, _other: &PhantomData<T>) -> Option<Ordering>
This method returns an ordering between self
and other
values if one exists. Read more
sourcefn lt(&self, other: &Rhs) -> bool
fn lt(&self, other: &Rhs) -> bool
This method tests less than (for self
and other
) and is used by the <
operator. Read more
sourcefn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
operator. Read more
sourceimpl<T> Serialize for PhantomData<T> where
T: ?Sized,
impl<T> Serialize for PhantomData<T> where
T: ?Sized,
sourcepub fn serialize<S>(
&self,
serializer: S
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
S: Serializer,
pub fn serialize<S>(
&self,
serializer: S
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
S: Serializer,
Serialize this value into the given Serde serializer. Read more
impl<T> Copy for PhantomData<T> where
T: ?Sized,
impl<T> EncodeLike<PhantomData<T>> for PhantomData<T>
impl<T> Eq for PhantomData<T> where
T: ?Sized,
impl<T> StructuralEq for PhantomData<T> where
T: ?Sized,
impl<T> StructuralPartialEq for PhantomData<T> where
T: ?Sized,
Auto Trait Implementations
impl<T: ?Sized> RefUnwindSafe for PhantomData<T> where
T: RefUnwindSafe,
impl<T: ?Sized> Send for PhantomData<T> where
T: Send,
impl<T: ?Sized> Sync for PhantomData<T> where
T: Sync,
impl<T: ?Sized> Unpin for PhantomData<T> where
T: Unpin,
impl<T: ?Sized> UnwindSafe for PhantomData<T> where
T: UnwindSafe,
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcepub fn borrow_mut(&mut self) -> &mut T
pub fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> CallHasher for T where
T: Hash,
impl<T> CallHasher for T where
T: Hash,
sourceimpl<T> CallHasher for T where
T: Hash + ?Sized,
impl<T> CallHasher for T where
T: Hash + ?Sized,
sourceimpl<T> CheckedConversion for T
impl<T> CheckedConversion for T
sourcefn checked_from<T>(t: T) -> Option<Self> where
Self: TryFrom<T>,
fn checked_from<T>(t: T) -> Option<Self> where
Self: TryFrom<T>,
Convert from a value of T
into an equivalent instance of Option<Self>
. Read more
sourcefn checked_into<T>(self) -> Option<T> where
Self: TryInto<T>,
fn checked_into<T>(self) -> Option<T> where
Self: TryInto<T>,
Consume self to return Some
equivalent value of Option<T>
. Read more
sourceimpl<T> DecodeLimit for T where
T: Decode,
impl<T> DecodeLimit for T where
T: Decode,
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Instruments this type with the provided Span
, returning an
Instrumented
wrapper. Read more
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<T, Outer> IsWrappedBy<Outer> for T where
Outer: AsRef<T> + AsMut<T> + From<T>,
T: From<Outer>,
impl<T, Outer> IsWrappedBy<Outer> for T where
Outer: AsRef<T> + AsMut<T> + From<T>,
T: From<Outer>,
sourceimpl<T> MallocSizeOfExt for T where
T: MallocSizeOf,
impl<T> MallocSizeOfExt for T where
T: MallocSizeOf,
sourcefn malloc_size_of(&self) -> usize
fn malloc_size_of(&self) -> usize
Method to launch a heapsize measurement with a fresh state. Read more
sourceimpl<T> SaturatedConversion for T
impl<T> SaturatedConversion for T
sourcefn saturated_from<T>(t: T) -> Self where
Self: UniqueSaturatedFrom<T>,
fn saturated_from<T>(t: T) -> Self where
Self: UniqueSaturatedFrom<T>,
Convert from a value of T
into an equivalent instance of Self
. Read more
sourcefn saturated_into<T>(self) -> T where
Self: UniqueSaturatedInto<T>,
fn saturated_into<T>(self) -> T where
Self: UniqueSaturatedInto<T>,
Consume self to return an equivalent value of T
. Read more
sourceimpl<T> ToOwned for T where
T: Clone,
impl<T> ToOwned for T where
T: Clone,
type Owned = T
type Owned = T
The resulting type after obtaining ownership.
sourcepub fn to_owned(&self) -> T
pub fn to_owned(&self) -> T
Creates owned data from borrowed data, usually by cloning. Read more
sourcepub fn clone_into(&self, target: &mut T)
pub fn clone_into(&self, target: &mut T)
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more
sourceimpl<S, T> UncheckedInto<T> for S where
T: UncheckedFrom<S>,
impl<S, T> UncheckedInto<T> for S where
T: UncheckedFrom<S>,
sourcepub fn unchecked_into(self) -> T
pub fn unchecked_into(self) -> T
The counterpart to unchecked_from
.
sourceimpl<T, S> UniqueSaturatedInto<T> for S where
T: Bounded,
S: TryInto<T>,
impl<T, S> UniqueSaturatedInto<T> for S where
T: Bounded,
S: TryInto<T>,
sourcepub fn unique_saturated_into(self) -> T
pub fn unique_saturated_into(self) -> T
Consume self to return an equivalent value of T
.