title: Rust function which mutates self and then returns an immutable reference, borrow checker says self is still borrowed mutably
body: <p>I have a function that I would like to mutate <code>self</code> and then return an immutable reference into <code>self</code>. In theory, I would think that the borrow checker could reason that the mutable reference only lives as long as the function body, and so from when the function exits to when it's return value is dropped <code>self</code> is only borrowed immutably. However, the compiler is telling me that <code>self</code> is borrowed mutably for the lifetime of the return value. Here's an example:</p>
  <pre class="lang-rust prettyprint-override"><code>#[derive(Debug)]
  struct Foo(i32);
  
  impl Foo {
      fn doo(&amp;mut self) -&gt; &amp;Self {
          self.0 += 1;
          self // implicit coercion
      }
  }
  
  fn main() {
      let mut foo = Foo(0);
      let bar = foo.doo();
      println!(&quot;{:?}, {:?}&quot;, &amp;foo, bar);
  }
  </code></pre>
  <p>In theory I think this could work since <code>&amp;foo</code> and <code>bar</code> are both <code>&amp;Foo</code>s so they can coexist, but this give the error message:</p>
  <pre class="lang-rust prettyprint-override"><code>error[E0502]: cannot borrow `foo` as immutable because it is also borrowed as mutable
    --&gt; src/main.rs:14:28
     |
  13 |     let bar = foo.doo();
     |               --------- mutable borrow occurs here
  14 |     println!(&quot;{:?}, {:?}&quot;, &amp;foo, bar);
     |                            ^^^^  --- mutable borrow later used here
     |                            |
     |                            immutable borrow occurs here
  
  For more information about this error, try `rustc --explain E0502`.
  </code></pre>
  <p>So is there a reason why the return value of <code>doo</code> must continue to borrow <code>self</code> mutably, or is there a way to get the behavior I want?</p>