title: Writing an iterator
body: <blockquote>
    <p>Editor's note: This code example is from a version of Rust prior to 1.0 and is not valid Rust 1.0 code. Updated versions of this code no longer produce an error due to changes how <code>for</code> loops are implemented. </p>
  </blockquote>
  
  <p>I'm writing a Vector struct in Rust. </p>
  
  <pre><code>pub struct Vector {
      pub x: f32,
      pub y: f32,
      pub z: f32,
  
      curr: uint
  }
  </code></pre>
  
  <p>And I'd like to write a simple iterator for it, so that I can iterate over the elements of the vector. It's occasionally useful, plus I know next to nothing about iterators in Rust.</p>
  
  <p>Here's what I've got at the moment.</p>
  
  <pre><code>impl Iterator&lt;f32&gt; for Vector {
      fn next(&amp;mut self) -&gt; Option&lt;f32&gt; {
          let new_next : Option&lt;f32&gt; = match self.curr {
              0 =&gt; Some(self.x),
              1 =&gt; Some(self.y),
              2 =&gt; Some(self.z), 
              _ =&gt; None
          };
          let new_curr = (self.curr + 1) % 4;
          mem::replace(&amp;mut self.curr, new_curr);
          new_next
      }
  }
  </code></pre>
  
  <p>Now ideally I'd like to be able to use this like:</p>
  
  <pre><code>let u = Vector::new(0.0f32, 0.0f32, 0.0f32);
  for element in u {
      ///
  }
  </code></pre>
  
  <p>However, I get the following compiler error:</p>
  
  <pre><code> error: cannot borrow immutable local variable `u` as mutable
  </code></pre>
  
  <p>So I'm stumped. After a couple hours of Googling, I couldn't come up with anything. I feel like I'm missing something huge. </p>