title: How to capture self consuming variable in a struct?
body: <p>I have a Reader instance with a method that <a href="https://github.com/estebank/galvanize/blob/0abafb62fec98f257ebd27124b66131ec5d6216f/src/reader.rs#L320" rel="nofollow">consumes the Reader and returns a Writer</a> and the Writer can similarly get back to a Reader again. It's trivial to use immutably, but I can't figure out how to hide the immutability from callers and just do the reader-writer-reader dance behind the scenes with a mutable Self.</p>
  
  <p>Essentially I'd like something like:</p>
  
  <pre><code>struct Container&lt;'a&gt; {
      reader: Reader&lt;'a, File&gt;
  }
  
  fn update(&amp;mut self) {
      let writer = self.reader.as_writer();
      writer.write_something();
      self.reader = writer.as_reader();
  }
  </code></pre>
  
  <p>which just gives <code>cannot move out of borrowed content</code> error. Tried to add a Box, Cell, or RefCell around the Reader which just lead to other errors.</p>
  
  <p>Can the <code>reader</code> be hidden behind a mutable interface or does it force the whole struct hierarchy to be mutable as well? (i.e. similar to IO in Haskell)</p>
  
  <hr>
  
  <p>Self contained sample with the types matching the real thing (I think)</p>
  
  <pre><code>#[derive(Debug)]
  struct NoCopy(u32);
  
  #[derive(Debug)]
  struct Flipper&lt;'a, T: 'a&gt; {
      data: &amp;'a mut T,
  }
  #[derive(Debug)]
  struct Flopper&lt;'a, T: 'a&gt; {
      data: &amp;'a mut T,
  }
  impl&lt;'a, T&gt; Flipper&lt;'a, T&gt; {
      fn flip(self) -&gt; Flopper&lt;'a, T&gt; {
          Flopper{data: self.data}
      }
  }
  impl&lt;'a, T&gt; Flopper&lt;'a, T&gt; {
      fn flop(self) -&gt; Flipper&lt;'a, T&gt; {
          Flipper{data: self.data}
      }
  }
  
  #[derive(Debug)]
  struct Container&lt;'a, T: 'a&gt; {
      flipper: Flipper&lt;'a, T&gt;,
  }
  impl&lt;'a, T&gt; Container&lt;'a, T&gt; {
      fn run(&amp;mut self) {
          self.flipper = self.flipper.flip().flop();
      }
  }
  
  fn main() {
      let f = Flipper{data: &amp;mut NoCopy(42)};
      let f = f.flip().flop();
      println!("f={:?}", f);
  
      let mut c = Container{flipper: f};
      c.run();
      println!("c={:?}", c);
  }
  </code></pre>
  
  <pre>
  error[E0507]: cannot move out of borrowed content
    --> src/main.rs:29:24
     |
  29 |         self.flipper = self.flipper.flip().flop();
     |                        ^^^^ cannot move out of borrowed content
  </pre>