Open In App

Rust – Phantom Type Parameter

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we have a concept of the Phantom type parameters. In phantom data types, various parameters have various generic hidden parameters that are usually extra and unknown to the users. These parameters hold no storage area in the memory. Phantom parameters are used for checking the codes during compile time and generally do not have any role to play during run time environments. For implementing Phantom parameters, we need to use std::marker::PhantomData for implementing the phantom type parameters.

Example 1:

Rust




// Rust - phantom type parameter
use std::marker::PhantomData;
 
#[derive(PartialEq)]
struct GfgPhantomTuple<X,Y>(X,PhantomData<Y>);
#[derive(PartialEq)]
struct GfgPhantomStruct<X,Y> {first: X, phantom: PhantomData<Y> }
fn main() {
    let _tuple1: GfgPhantomTuple<char, f32> = GfgPhantomTuple('A', PhantomData);
    let _tuple2: GfgPhantomTuple<char, f64> = GfgPhantomTuple('B', PhantomData);
 
    let _struct_one: GfgPhantomStruct<char, f32> = GfgPhantomStruct {
        first: 'A',
        phantom: PhantomData,
    };
    let _struct_two: GfgPhantomStruct<char, f64> = GfgPhantomStruct {
        first: 'B',
        phantom: PhantomData,
    };
 
}


Output:

Explanation:

In this example, we import the use std::marker::PhantomData from the Rust library. We declare a struct GfgPhantomStruct having two parameters X and Y and to use the struct we import the #[derive(PartialEq)] (which allows an equality test for this type). In this struct, we have declared first as X and the phantom data as Y. This struct is generic over ‘X’, and parameter Y is hidden with no storage allocated for parameter Y. As no storage is allocated for Y we do not use it for any computation purpose. 

Here, we have declared f32 and f64 respectively for the tuples(GfgPhantomTuple) and there are two structs as well that have the first parameter as “A” and another struct as the first parameter as “B”. The next parameter for both the structs is phantom data.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads