Phantom type parameters

A phantom type parameter is one that doesn’t show up at runtime,
but is checked statically (and only) at compile time.

Data types can use extra generic type parameters to act as markers
or to perform type checking at compile time. These extra parameters
hold no storage values, and have no runtime behavior.

In the following example, we combine std::marker::PhantomData
with the phantom type parameter concept to create tuples containing
different data types.

  1. use std::marker::PhantomData;
  2. // A phantom tuple struct which is generic over `A` with hidden parameter `B`.
  3. #[derive(PartialEq)] // Allow equality test for this type.
  4. struct PhantomTuple<A, B>(A,PhantomData<B>);
  5. // A phantom type struct which is generic over `A` with hidden parameter `B`.
  6. #[derive(PartialEq)] // Allow equality test for this type.
  7. struct PhantomStruct<A, B> { first: A, phantom: PhantomData<B> }
  8. // Note: Storage is allocated for generic type `A`, but not for `B`.
  9. // Therefore, `B` cannot be used in computations.
  10. fn main() {
  11. // Here, `f32` and `f64` are the hidden parameters.
  12. // PhantomTuple type specified as `<char, f32>`.
  13. let _tuple1: PhantomTuple<char, f32> = PhantomTuple('Q', PhantomData);
  14. // PhantomTuple type specified as `<char, f64>`.
  15. let _tuple2: PhantomTuple<char, f64> = PhantomTuple('Q', PhantomData);
  16. // Type specified as `<char, f32>`.
  17. let _struct1: PhantomStruct<char, f32> = PhantomStruct {
  18. first: 'Q',
  19. phantom: PhantomData,
  20. };
  21. // Type specified as `<char, f64>`.
  22. let _struct2: PhantomStruct<char, f64> = PhantomStruct {
  23. first: 'Q',
  24. phantom: PhantomData,
  25. };
  26. // Compile-time Error! Type mismatch so these cannot be compared:
  27. //println!("_tuple1 == _tuple2 yields: {}",
  28. // _tuple1 == _tuple2);
  29. // Compile-time Error! Type mismatch so these cannot be compared:
  30. //println!("_struct1 == _struct2 yields: {}",
  31. // _struct1 == _struct2);
  32. }

See also:

Derive, struct, and TupleStructs