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.

Layout

For all T, the following are guaranteed:

  • size_of::<PhantomData<T>>() == 0
  • align_of::<PhantomData<T>>() == 1

Trait Implementations§

§

impl<T> CanonicalDeserialize for PhantomData<T>where T: Send + Sync,

§

fn deserialize_with_mode<R>( _reader: R, _compress: Compress, _validate: Validate ) -> Result<PhantomData<T>, SerializationError>where R: Read,

The general deserialize method that takes in customization flags.
§

fn deserialize_compressed<R>(reader: R) -> Result<Self, SerializationError>where R: Read,

§

fn deserialize_compressed_unchecked<R>( reader: R ) -> Result<Self, SerializationError>where R: Read,

§

fn deserialize_uncompressed<R>(reader: R) -> Result<Self, SerializationError>where R: Read,

§

fn deserialize_uncompressed_unchecked<R>( reader: R ) -> Result<Self, SerializationError>where R: Read,

§

impl<T> CanonicalSerialize for PhantomData<T>

§

fn serialize_with_mode<W>( &self, _writer: W, _compress: Compress ) -> Result<(), SerializationError>where W: Write,

The general serialize method that takes in customization flags.
§

fn serialized_size(&self, _compress: Compress) -> usize

§

fn serialize_compressed<W>(&self, writer: W) -> Result<(), SerializationError>where W: Write,

§

fn compressed_size(&self) -> usize

§

fn serialize_uncompressed<W>(&self, writer: W) -> Result<(), SerializationError>where W: Write,

§

fn uncompressed_size(&self) -> usize

source§

impl<T> Clone for PhantomData<T>where T: ?Sized,

source§

fn clone(&self) -> PhantomData<T>

Returns a copy of the value. Read more
source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T> Debug for PhantomData<T>where T: ?Sized,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<'a, T> Decode<'a> for PhantomData<T>where T: ?Sized,

Dummy implementation for PhantomData which allows deriving implementations on structs with phantom fields.

§

fn decode<R>(_reader: &mut R) -> Result<PhantomData<T>, Error>where R: Reader<'a>,

Attempt to decode this message using the provided decoder.
§

fn from_der(bytes: &'a [u8]) -> Result<Self, Error>

Parse Self from the provided DER-encoded byte slice.
§

impl<T> Decode for PhantomData<T>

§

fn decode<I>(_input: &mut I) -> Result<PhantomData<T>, Error>where I: Input,

Attempt to deserialise the value from input.
§

fn decode_into<I>( input: &mut I, dst: &mut MaybeUninit<Self> ) -> Result<DecodeFinished, Error>where I: Input,

Attempt to deserialize the value from input into a pre-allocated piece of memory. Read more
§

fn skip<I>(input: &mut I) -> Result<(), Error>where I: Input,

Attempt to skip the encoded value from input. Read more
§

fn encoded_fixed_size() -> Option<usize>

Returns the fixed encoded size of the type. Read more
const: unstable · source§

impl<T> Default for PhantomData<T>where T: ?Sized,

const: unstable · source§

fn default() -> PhantomData<T>

Returns the “default value” for a type. Read more
§

impl<T> DerOrd for PhantomData<T>

Provide a no-op implementation for PhantomData

§

fn der_cmp(&self, _other: &PhantomData<T>) -> Result<Ordering, Error>

Return an Ordering between self and other when serialized as ASN.1 DER.
source§

impl<'de, T> Deserialize<'de> for PhantomData<T>where T: ?Sized,

source§

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
source§

impl<'de, T> DeserializeSeed<'de> for PhantomData<T>where T: Deserialize<'de>,

§

type Value = T

The type produced by using this seed.
source§

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.
§

impl<T> Encode for PhantomData<T>

§

fn encode_to<W>(&self, _dest: &mut W)where W: Output + ?Sized,

Convert self to a slice and append it to the destination.
§

fn size_hint(&self) -> usize

If possible give a hint of expected size of the encoding. Read more
§

fn encode(&self) -> Vec<u8, Global>

Convert self to an owned vector.
§

fn using_encoded<R, F>(&self, f: F) -> Rwhere F: FnOnce(&[u8]) -> R,

Convert self to a slice and then invoke the given closure with it.
§

fn encoded_size(&self) -> usize

Calculates the encoded size. Read more
§

impl<T> Encode for PhantomData<T>where T: ?Sized,

Dummy implementation for PhantomData which allows deriving implementations on structs with phantom fields.

§

fn encoded_len(&self) -> Result<Length, Error>

Compute the length of this value in bytes when encoded as ASN.1 DER.
§

fn encode(&self, _writer: &mut impl Writer) -> Result<(), Error>

Encode this value as ASN.1 DER using the provided [Writer].
§

fn encode_to_slice<'a>(&self, buf: &'a mut [u8]) -> Result<&'a [u8], Error>

Encode this value to the provided byte slice, returning a sub-slice containing the encoded message.
§

fn encode_to_vec(&self, buf: &mut Vec<u8, Global>) -> Result<Length, Error>

Encode this message as ASN.1 DER, appending it to the provided byte vector.
§

fn to_der(&self) -> Result<Vec<u8, Global>, Error>

Encode this type as DER, returning a byte vector.
source§

impl<T> Hash for PhantomData<T>where T: ?Sized,

source§

fn hash<H>(&self, _: &mut H)where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

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

Feeds a slice of this type into the given Hasher. Read more
§

impl<T> MaxEncodedLen for PhantomData<T>

§

fn max_encoded_len() -> usize

Upper bound, in bytes, of the maximum encoded size of this item.
source§

impl<T> Ord for PhantomData<T>where T: ?Sized,

source§

fn cmp(&self, _other: &PhantomData<T>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Selfwhere Self: Sized,

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

fn min(self, other: Self) -> Selfwhere Self: Sized,

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

fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl<T> PalletError for PhantomData<T>

source§

const MAX_ENCODED_SIZE: usize = 0usize

The maximum encoded size for the implementing type. Read more
source§

impl<T> PartialEq<PhantomData<T>> for PhantomData<T>where T: ?Sized,

source§

fn eq(&self, _other: &PhantomData<T>) -> bool

This method tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T> PartialOrd<PhantomData<T>> for PhantomData<T>where T: ?Sized,

source§

fn partial_cmp(&self, _other: &PhantomData<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
source§

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
source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<T> Serialize for PhantomData<T>where T: ?Sized,

source§

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> TypeInfo for PhantomData<T>

§

type Identity = PhantomData<()>

The type identifying for which type info is provided. Read more
§

fn type_info() -> Type<MetaForm>

Returns the static type identifier for Self.
§

impl<T> Valid for PhantomData<T>where T: Sync,

§

fn check(&self) -> Result<(), SerializationError>

§

fn batch_check<'a>( batch: impl Iterator<Item = &'a Self> + Send ) -> Result<(), SerializationError>where Self: 'a,

§

impl<T> ValueOrd for PhantomData<T>

Provide a no-op implementation for PhantomData

§

fn value_cmp(&self, _other: &PhantomData<T>) -> Result<Ordering, Error>

Return an Ordering between value portion of TLV-encoded self and other when serialized as ASN.1 DER.
§

impl<Z> Zeroize for PhantomData<Z>

PhantomData is always zero sized so provide a [Zeroize] implementation.

§

fn zeroize(&mut self)

Zero out this object from memory using Rust intrinsics which ensure the zeroization operation is not “optimized away” by the compiler.
§

impl<T> ConstEncodedLen for PhantomData<T>where T: ConstEncodedLen,

source§

impl<T> Copy for PhantomData<T>where T: ?Sized,

§

impl<T> EncodeLike<PhantomData<T>> for PhantomData<T>

source§

impl<T> Eq for PhantomData<T>where T: ?Sized,

source§

impl<T> StructuralEq for PhantomData<T>where T: ?Sized,

source§

impl<T> StructuralPartialEq for PhantomData<T>where T: ?Sized,

§

impl<Z> ZeroizeOnDrop for PhantomData<Z>

[PhantomData is always zero sized so provide a ZeroizeOnDrop implementation.

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§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> CallHasher for Twhere T: Hash + ?Sized,

§

fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher,

§

impl<T> CanonicalSerializeHashExt for Twhere T: CanonicalSerialize,

§

fn hash<H>(&self) -> GenericArray<u8, <H as OutputSizeUser>::OutputSize>where H: Digest,

§

fn hash_uncompressed<H>( &self ) -> GenericArray<u8, <H as OutputSizeUser>::OutputSize>where H: Digest,

source§

impl<T> CheckedConversion for T

source§

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
source§

fn checked_into<T>(self) -> Option<T>where Self: TryInto<T>,

Consume self to return Some equivalent value of Option<T>. Read more
source§

impl<T> Clear for Twhere T: Default + Eq + PartialEq<T>,

source§

fn is_clear(&self) -> bool

True iff no bits are set.
source§

fn clear() -> T

Return the value of Self that is clear.
§

impl<T> DecodeAll for Twhere T: Decode,

§

fn decode_all(input: &mut &[u8]) -> Result<T, Error>

Decode Self and consume all of the given input data. Read more
§

impl<T> DecodeLimit for Twhere T: Decode,

§

fn decode_all_with_depth_limit( limit: u32, input: &mut &[u8] ) -> Result<T, Error>

Decode Self and consume all of the given input data. Read more
§

fn decode_with_depth_limit<I>(limit: u32, input: &mut I) -> Result<T, Error>where I: Input,

Decode Self with the given maximum recursion depth and advance input by the number of bytes consumed. Read more
source§

impl<T> DynClone for Twhere T: Clone,

source§

fn __clone_box(&self, _: Private) -> *mut ()

source§

impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
§

impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

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

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

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

source§

impl<T, Outer> IsWrappedBy<Outer> for Twhere Outer: AsRef<T> + AsMut<T> + From<T>, T: From<Outer>,

source§

fn from_ref(outer: &Outer) -> &T

Get a reference to the inner from the outer.

source§

fn from_mut(outer: &mut Outer) -> &mut T

Get a mutable reference to the inner from the outer.

§

impl<T> KeyedVec for Twhere T: Codec,

§

fn to_keyed_vec(&self, prepend_key: &[u8]) -> Vec<u8, Global>

Return an encoding of Self prepended by given slice.
§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
source§

impl<T> SaturatedConversion for T

source§

fn saturated_from<T>(t: T) -> Selfwhere Self: UniqueSaturatedFrom<T>,

Convert from a value of T into an equivalent instance of Self. Read more
source§

fn saturated_into<T>(self) -> Twhere Self: UniqueSaturatedInto<T>,

Consume self to return an equivalent value of T. Read more
source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

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

fn clone_into(&self, target: &mut T)

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

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

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<S, T> UncheckedInto<T> for Swhere T: UncheckedFrom<S>,

source§

fn unchecked_into(self) -> T

The counterpart to unchecked_from.
source§

impl<T, S> UniqueSaturatedInto<T> for Swhere T: Bounded, S: TryInto<T>,

source§

fn unique_saturated_into(self) -> T

Consume self to return an equivalent value of T.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
§

impl<S> Codec for Swhere S: Decode + Encode,

§

impl<T> DecodeOwned for Twhere T: for<'a> Decode<'a>,

source§

impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>,

§

impl<T> EncodeLike<&&T> for Twhere T: Encode,

§

impl<T> EncodeLike<&T> for Twhere T: Encode,

§

impl<T> EncodeLike<&mut T> for Twhere T: Encode,

§

impl<T> EncodeLike<Arc<T>> for Twhere T: Encode,

§

impl<T> EncodeLike<Box<T, Global>> for Twhere T: Encode,

§

impl<'a, T> EncodeLike<Cow<'a, T>> for Twhere T: ToOwned + Encode,

§

impl<T> EncodeLike<Rc<T>> for Twhere T: Encode,

§

impl<S> FullCodec for Swhere S: Decode + FullEncode,

§

impl<S> FullEncode for Swhere S: Encode + EncodeLike<S>,

§

impl<T> JsonSchemaMaybe for T

§

impl<T> MaybeDebug for Twhere T: Debug,

source§

impl<T> MaybeHash for Twhere T: Hash,

source§

impl<T> MaybeHash for Twhere T: Hash,

source§

impl<T> MaybeRefUnwindSafe for Twhere T: RefUnwindSafe,

source§

impl<T> MaybeSerialize for Twhere T: Serialize,

source§

impl<T> MaybeSerializeDeserialize for Twhere T: DeserializeOwned + Serialize,

source§

impl<T> Member for Twhere T: Send + Sync + Debug + Eq + PartialEq<T> + Clone + 'static,

source§

impl<T> Parameter for Twhere T: Codec + EncodeLike<T> + Clone + Eq + Debug + TypeInfo,

§

impl<T> StaticTypeInfo for Twhere T: TypeInfo + 'static,