PhantomData is a tag structure of zero size type.
Function:
- A type that is not used;
- Type variable;
- Mark ownership relationship;
- Automatic trait implementation (send/sync);
Type not used
The life cycle
struct Slice<'a, T> {
start: *const T,
end: *const T,
}
Copy the code
However, because ‘a ‘is not used in the structure, it is unbounded. Disallow infinite lifecycles and types in structure definitions.
Modified as follows:
use std::marker;
struct Iter<'a, T: 'a> {
ptr: *const T,
end: *const T,
_marker: marker::PhantomData<&'a T>,
}
Copy the code
type
pub struct RetryableSendCh<T, C: Sender<T>> {
ch: C,
name: &'static str,
marker: PhantomData<T>,
}
Copy the code
Token ownership relationship
struct Vec<T> {
data: *const T, // *const for variance!
len: usize,
cap: usize,}Copy the code
Native Pointers have no ownership semantics, and the DROP inspector will assume that Vec
does not have any values of type T. This in turn will make it unnecessary for Vec to worry about discarding any T in its destructor. But it’s possible that T will be released early. In order to drop the inspector that VEC must have the data of T, modify it as follows:
use std::marker;
struct Vec<T> {
data: *const T, // *const for variance!
len: usize,
cap: usize,
_marker: marker::PhantomData<T>,
}
Copy the code
Type variable
- The same
If you cannot replace one type with another, the type is called immutable.
- inverter
Can be replaced by its base class.
- covariance
Can be replaced by a derived type.
PhantomData
Schema table
Here’s a table of all the methods PhantomData can use:
Phantom type | 'a |
T |
---|---|---|
PhantomData<T> |
– | variant (with drop check) |
PhantomData<&'a T> |
variant | variant |
PhantomData<&'a mut T> |
variant | invariant |
PhantomData<*const T> |
– | variant |
PhantomData<*mut T> |
– | invariant |
PhantomData<fn(T)> |
– | contravariant (*) |
PhantomData<fn() -> T> |
– | variant |
PhantomData<fn(T) -> T> |
– | invariant |
PhantomData<Cell<&'a ()>> |
invariant | – |
(*) This will remain constant if inversion is abolished.