5

I was browsing some libraries and I noticed the usage of a struct containing a phantom lifetime field, like

struct S<'a> {
    s: i32,
    _lifetime: PhantomData<&'a ()> // NOTE: there's no generic type here!
}

I'm curious to know the significance of the phantom lifetime — what advantages does it provide for S and that without it would not be possible or not convenient to deal with?

Ehsan M. Kermani
  • 912
  • 2
  • 12
  • 26

1 Answers1

9

It's the same as using PhantomData for a generic type: to make the struct act as if it contains a reference even though the compiler doesn't see one in the struct definition.

A big reason you'd use this is to represent related lifetimes when dealing with FFI types, but it's useful any time where you want the protection provided by lifetimes but you don't actually have something to take a reference of.

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Great! thank you for the explanations. I'll need to look into the links. I guess FFI was the main reason for using it in that library. I've also corrected my note above. – Ehsan M. Kermani Aug 02 '18 at 03:28