title: How exactly does PhantomData work in Rust?
body: <p>I find the concept of <code>PhantomData</code> in Rust quite confusing. I use it extensively to constrain object lifetimes in my FFI-based code, and I am still not sure whether I do it correctly or not.</p>
  
  <p>Here's a contrived sample of how I often end up using it. For example, I do not want an instance of <code>MyStruct</code> to outlive an instance of <code>Context</code>:</p>
  
  <pre class="lang-rust prettyprint-override"><code>// FFI declarations and types
  mod ffi {
      use std::ffi::c_void;
      pub type handle_t = *const c_void;
      // ...
  }
  
  // A wrapper structure for some context created and maintained
  // inside the C library
  struct Context {
      // ...
  }
  
  // Handle is only valid as long as the Context is alive.
  // Hence, I use the PhantomData marker to constrain its lifetime.
  struct MyStruct&lt;'a&gt; {
      marker: PhantomData&lt;&amp;'a Context&gt;,
      handle: ffi::handle_t,
  }
  
  impl&lt;'a&gt; MyStruct&lt;'a&gt; {
      fn new(context: &amp;'a Context) -&gt; Self {
          let handle: ffi::handle_t = context.new_handle();
          MyStruct {
              marker: PhantomData,
              handle
          }
      }
  }
  
  fn main() {
      // Initialize the context somewhere inside the C library
      let ctx = Context::new(unsafe {ffi::create_context()});
  
      // Create an instance of MyStruct
      let my_struct = MyStruct::new(&amp;ctx);
  
      // ...
  }
  </code></pre>
  
  <p>I don't quite understand the following:</p>
  
  <ol>
  <li><p>What exactly is this <code>marker: PhantomData</code> thing, syntactically? I mean, it does not look like a constructor, which I'd expect to be something like <code>PhantomData{}</code> or <code>PhantomData()</code>.</p></li>
  <li><p>For the purposes of lifetime tracking, does <code>PhantomData</code> even care about the actual type in the declaration of <code>marker</code>? I tried changing it to <code>PhantomData&lt;&amp;'a usize&gt;</code>, and it still worked.</p></li>
  <li><p>In the declaration of my <code>MyStruct::new()</code> method, if I forget to explicitly specify the <code>'a</code> lifetime for the <code>context</code> argument, the magic of <code>PhantomData</code> disappears, and it becomes OK to drop <code>Context</code> before <code>MyStruct</code>. This is quite insidious; the compiler does not even give a warning. What lifetime does it assign to <code>marker</code> then, and why? </p></li>
  <li><p>Related to the previous question; if there are multiple input reference arguments with potentially different lifetimes, how does <code>PhantomData</code> determine which lifetime to use?</p></li>
  </ol>