title: Borrowing the mutable member used inside the loop
body: <p>The problem I want to solve is:</p>
  
  <blockquote>
    <p>Given the recursively nested data structure, eg. a JSON tree, and a path pointing to (possibly non-existent) element inside it, return the mutable reference of the element, that's the closest to given path.</p>
  </blockquote>
  
  <p>Example: if we have JSON document in form <code>{ a: { b: { c: "foo" } } }</code> and a path <code>a.b.d</code>, we want to have a mutable pointer to value stored under key "b".</p>
  
  <p>This is a code snippet, what I've got so far:</p>
  
  <pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;
  
  enum Json {
      Number(i64),
      Bool(bool),
      String(String),
      Array(Vec&lt;Json&gt;),
      Object(HashMap&lt;String, Json&gt;)
  }
  
  struct Pointer&lt;'a, 'b&gt; {
      value: &amp;'a mut Json,
      path: Vec&lt;&amp;'b str&gt;,
      position: usize
  }
  
  /// Return a mutable pointer to JSON element having shared 
  /// the nearest common path with provided JSON. 
  fn nearest_mut&lt;'a,'b&gt;(obj: &amp;'a mut Json, path: Vec&lt;&amp;'b str&gt;) -&gt; Pointer&lt;'a,'b&gt; {
      let mut i = 0;
      let mut current = obj;
      for &amp;key in path.iter() {
          match current {
              Json::Array(array) =&gt; {
                  match key.parse::&lt;usize&gt;() {
                      Ok(index) =&gt; {
                          match array.get_mut(index) {
                              Some(inner) =&gt; current = inner,
                              None =&gt; break,
                          }
                      },
                      _ =&gt; break,
                  }
              } ,
              Json::Object(map) =&gt; {
                  match map.get_mut(key) {
                      Some(inner) =&gt; current = inner,
                      None =&gt; break
                  }
              },
              _ =&gt; break,
          };
          i += 1;
      }
      Pointer { path, position: i, value: current }
  }
  </code></pre>
  
  <p>The problem is that this doesn't pass through Rust's borrow checker, as <code>current</code> is borrowed as mutable reference twice, once inside match statement and once at the end of the function, when constructing the pointer method.</p>
  
  <p>I've tried a different approaches, but not figured out how to achieve the goal (maybe going the unsafe path).</p>