title: In Rust, is Option compiled to a runtime check or an instruction jump?
body: <p>In Rust, <code>Option</code> is defined as:</p>
  
  <pre><code>pub enum Option&lt;T&gt; {
      None,
      Some(T),
  }
  </code></pre>
  
  <p>Used like so:</p>
  
  <pre><code>fn may_return_none() -&gt; Option&lt;i32&gt; {
      if is_full_moon {
          None
      } else {
          Some(1)
      }
  }
  
  fn main() {
      let optional = may_return_none();
      match optional {
          None =&gt; println!("None"),
          Some(v) =&gt; println!("Some"),
      }
  }
  </code></pre>
  
  <p>I'm not familiar with Rust internals, but initially I assumed it might work similar to <code>Nullable</code> in .NET, so the compiled logic of my above Rust code would be like so:</p>
  
  <pre class="lang-cs prettyprint-override"><code>// occupies `sizeof(T) + 1` memory space, possibly more depending on `Bool`'s alignment, so `Nullable&lt;Int32&gt;` consumes 5 bytes.
  struct Nullable&lt;T&gt; {
      Bool hasValue;
      T value;
  }
  
  Nullable&lt;Int32&gt; MayReturnNone() {
      if( isFullMoon )
          // as a `struct`, the Nullable&lt;Int32&gt; instance is returned via the stack
          return Nullable&lt;Int32&gt;() { HasValue = false }
      else
          return Nullable&lt;Int32&gt;() { HasValue = true, Value = 1 }
  }
  
  void Test() {
      Nullable&lt;Int32&gt; optional = may_return_none();
      if( !optional.HasValue ) println("None");
      else                     println("Some");
  }
  </code></pre>
  
  <p>However this isn't a zero-cost abstraction because of the space required for the <code>Bool hasValue</code> flag - and Rust makes a point of providing zero-cost abstractions.</p>
  
  <p>I realise that <code>Option</code> could be implemented via a direct return-jump by the compiler, though it would need the exact jump-to values to be provided as arguments on the stack - as though you can push multiple return addresses:</p>
  
  <p>(Psuedocode)</p>
  
  <pre><code>mayReturnNone(returnToIfNone, returnToIfHasValue) {
  
      if( isFullMoon ) {
          cleanup-current-stackframe
          jump-to returnToIfNone
      else {
          cleanup-current-stackframe
          push-stack 1
          jump-to returnToIfHasValue
      }
  
  test() {
  
      mayReturnNone( instructionAddressOf( ifHasValue ), instructionAddressOf( ifNoValue ) )
  ifHasValue:
      println("Some")
  ifNoValue:
      println("None")
  }
  </code></pre>
  
  <p>Is this how it's implemented? This approach also works for other <code>enum</code> types in Rust - but this specific application I've demonstrated is very brittle and breaks if you want to execute code in-between the call to <code>mayReturnNone</code> and the <code>match</code> statement, for example (as <code>mayReturnNone</code> will jump directly to the <code>match</code>, skipping intermediate instructions).</p>