std::marker::PhantomData - Rust
Description: API documentation for the Rust `PhantomData` struct in crate `std`.
Keywords: rust, rustlang, rust-lang, PhantomData

# 1.0.0[−][src]Struct std::marker::PhantomData

    #[lang = "phantom_data"]pub struct PhantomData<T>
     where
        T: ?Sized;

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:

ⓘThis example deliberately fails to compile

    struct Slice<'a, T> {
        start: *const T,
        end: *const T,
    }

Run

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>,
    }

Run

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,
        }
    }

Run

## 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);
        }
    }

Run

## 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

### `impl<T> Clone for PhantomData<T> where
T: ?Sized,` [src]

#### `fn clone(&self) -> PhantomData<T>`[src]

Returns a copy of the value. Read more

#### `fn clone_from(&mut self, source: &Self)`[src]

Performs copy-assignment from `source`. Read more

### `impl<T> Copy for PhantomData<T> where
T: ?Sized,` [src]

### `impl<T> Debug for PhantomData<T> where
T: ?Sized,` [src]

#### `fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>`[src]

Formats the value using the given formatter. Read more

### `impl<T> Default for PhantomData<T> where
T: ?Sized,` [src]

#### `fn default() -> PhantomData<T>`[src]

Returns the "default value" for a type. Read more

### `impl<T> Eq for PhantomData<T> where
T: ?Sized,` [src]

### `impl<T> Hash for PhantomData<T> where
T: ?Sized,` [src]

#### `fn hash<H>(&self, &mut H) where
H: Hasher,` [src]

Feeds this value into the given `Hasher`. Read more

#### `fn hash_slice<H>(data: &[Self], state: &mut H) where
H: Hasher,` 1.3.0[src]

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

### `impl<T> Ord for PhantomData<T> where
T: ?Sized,` [src]

#### `fn cmp(&self, _other: &PhantomData<T>) -> Ordering`[src]

This method returns an `Ordering` between `self` and `other`. Read more

#### `#[must_use]fn max(self, other: Self) -> Self`1.21.0[src]

Compares and returns the maximum of two values. Read more

#### `#[must_use]fn min(self, other: Self) -> Self`1.21.0[src]

Compares and returns the minimum of two values. Read more

#### `#[must_use]fn clamp(self, min: Self, max: Self) -> Self`[src]

🔬 This is a nightly-only experimental API. (`clamp` #44095)

Restrict a value to a certain interval. Read more

### `impl<T> PartialEq<PhantomData<T>> for PhantomData<T> where
T: ?Sized,` [src]

#### `fn eq(&self, _other: &PhantomData<T>) -> bool`[src]

This method tests for `self` and `other` values to be equal, and is used by `==`. Read more

#### `#[must_use]fn ne(&self, other: &Rhs) -> bool`[src]

This method tests for `!=`.

### `impl<T> PartialOrd<PhantomData<T>> for PhantomData<T> where
T: ?Sized,` [src]

#### `fn partial_cmp(&self, _other: &PhantomData<T>) -> Option<Ordering>`[src]

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

#### `#[must_use]fn lt(&self, other: &Rhs) -> bool`[src]

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

#### `#[must_use]fn le(&self, other: &Rhs) -> bool`[src]

This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more

#### `#[must_use]fn gt(&self, other: &Rhs) -> bool`[src]

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

#### `#[must_use]fn ge(&self, other: &Rhs) -> bool`[src]

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

### `impl<T> StructuralEq for PhantomData<T> where
T: ?Sized,` [src]

### `impl<T> StructuralPartialEq for PhantomData<T> where
T: ?Sized,` [src]

## 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

### `impl<T> Any for T where
T: 'static + ?Sized,` [src]

#### `fn type_id(&self) -> TypeId`[src]

Gets the `TypeId` of `self`. Read more

### `impl<T> Borrow<T> for T where
T: ?Sized,` [src]

#### `fn borrow(&self) -> &Tⓘ

### Notable traits for &'_ mut F

`impl<'_, F> Future for &'_ mut F where
F: Unpin + Future + ?Sized, type Output = <F as Future>::Output;impl<'_, I> Iterator for &'_ mut I where
I: Iterator + ?Sized, type Item = <I as Iterator>::Item;impl<R: Read + ?Sized, '_> Read for &'_ mut Rimpl<W: Write + ?Sized, '_> Write for &'_ mut W`
`[src]

Immutably borrows from an owned value. Read more

### `impl<T> BorrowMut<T> for T where
T: ?Sized,` [src]

#### `fn borrow_mut(&mut self) -> &mut Tⓘ

### Notable traits for &'_ mut F

`impl<'_, F> Future for &'_ mut F where
F: Unpin + Future + ?Sized, type Output = <F as Future>::Output;impl<'_, I> Iterator for &'_ mut I where
I: Iterator + ?Sized, type Item = <I as Iterator>::Item;impl<R: Read + ?Sized, '_> Read for &'_ mut Rimpl<W: Write + ?Sized, '_> Write for &'_ mut W`
`[src]

Mutably borrows from an owned value. Read more

### `impl<T> From<T> for T`[src]

#### `fn from(t: T) -> T`[src]

Performs the conversion.

### `impl<T, U> Into<U> for T where
U: From<T>,` [src]

#### `fn into(self) -> U`[src]

Performs the conversion.

### `impl<T> ToOwned for T where
T: Clone,` [src]

#### `type Owned = T`

The resulting type after obtaining ownership.

#### `fn to_owned(&self) -> T`[src]

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

#### `fn clone_into(&self, target: &mut T)`[src]

🔬 This is a nightly-only experimental API. (`toowned_clone_into` #41263)

recently added

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

### `impl<T, U> TryFrom<U> for T where
U: Into<T>,` [src]

#### `type Error = Infallible`

The type returned in the event of a conversion error.

#### `fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>`[src]

Performs the conversion.

### `impl<T, U> TryInto<U> for T where
U: TryFrom<T>,` [src]

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

The type returned in the event of a conversion error.

#### `fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>`[src]

Performs the conversion.