Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhantomData type usage in rust

I was going through some rust source code and I found a data type called PhantomData. I was going through the rust documentation and searched through the internet a lot. However, I couldn't understand the actual use of this data type with rust. If possible, could somebody please explain me this in simple manner?

pub struct GPIOD {
   _marker: PhantomData<*const ()>,
}
like image 823
hEShaN Avatar asked Dec 18 '22 15:12

hEShaN


1 Answers

The PhantomData struct is meant to signal to the compiler that a type or lifetime is being used in some way that is transparent to the compiler.

To quote the docs:

Adding a PhantomData 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 example, if we look at the iterator type for a slice [T]: std::slice::Iter<'a, T> and its declaration using the src button we'll see that it's actually declared as such:

struct Iter<'a, T: 'a> {
    start: *const T,
    end: *const T,
    _phantom: PhantomData<&'a T>,
}

std makes frequent use of pointer arithmetic to make optimizations more readily available (Although that is not to endorse the usage of pointer arithmetic in user code). In this case, we need to assure ourselves that the data that is pointed to by the two raw pointers (Which carry no lifetimes) outlive the struct, so we keep a PhantomData<&'a T> to tell the compiler to act like as if Iter owned a &'a T therefore enforcing lifetime rules for it.

like image 101
Optimistic Peach Avatar answered Jan 03 '23 00:01

Optimistic Peach