title: How to implement idiomatic operator overloading for values and references in Rust?
body: <p>When implementing a primitive fixed-size vector type (<code>float2</code> for example), I want to support the <code>Add</code> and <code>Sub</code> traits. Later, I will want to support <code>Mul</code> and <code>*Assign</code>.</p>
  
  <p>Looking up the documentation and other examples, I came up with this:</p>
  
  <pre><code>use std::ops::{Add, Sub};
  
  #[derive(Copy, Clone)]
  struct float2(f64, f64);
  
  impl Add for float2 {
      type Output = float2;
      fn add(self, _rhs: float2) -&gt; float2 {
          float2(self.0 + _rhs.0, self.1 + _rhs.1)
      }
  }
  
  impl Sub for float2 {
      type Output = float2;
      fn sub(self, _rhs: float2) -&gt; float2 {
          float2(self.0 - _rhs.0, self.1 - _rhs.1)
      }
  }
  </code></pre>
  
  <p>This works for basic examples, however I found in practice I would often end up with references passed in as arguments as well as local <code>float2</code>'s on the stack.</p>
  
  <p>To mix these I needed to either:</p>
  
  <ul>
  <li>De-reference variables (OK but makes code a little less readable).</li>
  <li>Declare operator overloading combinations of references too.</li>
  </ul>
  
  <p>Example:</p>
  
  <pre><code>impl&lt;'a, 'b&gt; Add&lt;&amp;'b float2&gt; for &amp;'a float2 {
      type Output = float2;
      fn add(self, _rhs: &amp;'b float2) -&gt; float2 {
          float2(self.0 + _rhs.0, self.1 + _rhs.1)
      }
  }
  impl&lt;'a&gt; Add&lt;float2&gt; for &amp;'a float2 {
      type Output = float2;
      fn add(self, _rhs: float2) -&gt; float2 {
          float2(self.0 + _rhs.0, self.1 + _rhs.1)
      }
  }
  impl&lt;'b&gt; Add&lt;&amp;'b float2&gt; for float2 {
      type Output = float2;
      fn add(self, _rhs: &amp;'b float2) -&gt; float2 {
          float2(self.0 + _rhs.0, self.1 + _rhs.1)
      }
  }
  
  /*... and again for Sub */
  </code></pre>
  
  <p>While this allows to write expressions without de-referencing. it becomes quite tedious to enumerate each combinations, especially when adding more operations &amp; types (<code>float3</code>, <code>float4</code>...).</p>
  
  <p>Is there a generally accepted way to...</p>
  
  <ul>
  <li>Automatically coerce types for operator overloading?</li>
  <li>Use macros or some other feature of the language to avoid tedious repetition?</li>
  </ul>
  
  <p>Or is it expected that developers either:</p>
  
  <ul>
  <li>Explicitly access variables as references as needed.</li>
  <li>Explicitly de-reference variables as needed.</li>
  <li>Write a lot of repetitive operator overloading functions.</li>
  </ul>
  
  <hr>
  
  <p><em>Note, I'm currently a beginner, I've checked some quite advanced math libraries in Rust, they're way over my head, while I could use them - I would like to understand how to write operator overloading for my own types.</em></p>