title: Newtype as generic parameter in Rust?
body: <p>Suppose I have the following newtype:</p>
  
  <pre><code>pub struct Num(pub i32);
  </code></pre>
  
  <p>Now, I have a function which accepts an optional <code>Num</code>:</p>
  
  <pre><code>pub fn calc(nu: Option&lt;Num&gt;) -&gt; i32 {
      let real_nu = match nu { // extract the value inside Num
          Some(nu) =&gt; nu.0,
          None     =&gt; -1
      };
      // performs lots of complicated calculations...
      real_nu * 1234
  }
  </code></pre>
  
  <p>What I want to write is a generic <code>extract</code> function like the one below (which won't compile):</p>
  
  <pre><code>// T here would be "Num" newtype
  // R would be "i32", which is wrapped by "Num"
  
  pub fn extract&lt;T, R&gt;(val: Option&lt;T&gt;) -&gt; R {
      match val {
          Some(val) =&gt; val.0, // return inner number
          None      =&gt; -1 as R
      }
  }
  </code></pre>
  
  <p>So that I can bypass the <code>match</code> inside my calc function:</p>
  
  <pre><code>pub fn calc(nu: Option&lt;Num&gt;) -&gt; i32 {
      // do a lot of complicated calculations...
      extract(nu) * 1234 // automatically extract i32 or -1
  }
  </code></pre>
  
  <p>How can I write <code>extract</code>?</p>
  
  <p><strong>Motivation:</strong> in the program I'm writing, there are several newtypes like <code>Num</code>, and they wrap <code>i8</code>, <code>i16</code> and <code>i32</code>. And there are many different <code>calc</code> functions. It's getting very repetitive to write all these <code>match</code>es at the begining of each <code>calc</code> function.</p>