title: Encapsulating sequentially initialized state with self-references in Rust struct
body: <p>I'm trying to define a struct that can act as an iterator for a <code>Vec</code> that is held within a <code>RefCell</code>:</p>
  
  <pre><code>use std::slice::Iter;
  use std::cell::Ref;
  use std::cell::RefCell;
  
  struct HoldsVecInRefCell {
      vec_in_refcell: RefCell&lt;Vec&lt;i32&gt;&gt;,
  }
  
  // TODO: struct HoldsVecInRefCellIter implementing Iterator ...
  
  impl HoldsVecInRefCell {
      fn new() -&gt; HoldsVecInRefCell {
          HoldsVecInRefCell { vec_in_refcell: RefCell::new(Vec::new()) }
      }
  
      fn add_int(&amp;self, i: i32) {
          self.vec_in_refcell.borrow_mut().push(i);
      }
  
      fn iter(&amp;self) -&gt; HoldsVecInRefCellIter {
          // TODO ...
      }
  }
  
  fn main() {
      let holds_vec = HoldsVecInRefCell::new();
      holds_vec.add_int(1);
      holds_vec.add_int(2);
      holds_vec.add_int(3);
  
      let mut vec_iter = holds_vec.iter();  // Under the hood: run-time borrow check
  
      for i in vec_iter {
          println!("{}", i);
      }
  }
  </code></pre>
  
  <p>By comparison,<code>vec_iter</code> can be initialized in-line in <code>main()</code> as follows (deliberately verbose):</p>
  
  <pre><code>// Elided: lifetime parameter of Ref
  let vec_ref: Ref&lt;Vec&lt;i32&gt;&gt; = holds_vec.vec_in_refcell.borrow();
  // Elided: lifetime parameter of Iter
  let mut vec_iter: Iter&lt;i32&gt; = vec_ref.iter();
  </code></pre>
  
  <p>Is there any way to define a struct implementing <code>Iterator</code> that holds both the <code>Ref</code> (to keep the immutable <code>RefCell</code> borrow alive) and the <code>Iter</code> (to maintain iterator state for <code>next()</code>, rather than rolling my own iterator for <code>Vec</code> or whatever other container), when the second is derived from (and holds a reference obtained from) the first?</p>
  
  <p>I've tried several approaches to implementing this, and all run afoul of the borrow checker. If I put both pieces of state as bare struct members, like</p>
  
  <pre><code>struct HoldsVecInRefCellIter&lt;'a&gt; {
      vec_ref: Ref&lt;'a, Vec&lt;i32&gt;&gt;,
      vec_iter: Iter&lt;'a, i32&gt;,
  }
  </code></pre>
  
  <p>then I can't initialize both fields at once with <code>HoldsVecInRefCellIter { ... }</code> syntax (see e.g., <a href="https://stackoverflow.com/questions/27163593/does-rust-have-syntax-for-initializing-a-struct-field-with-an-earlier-field">Does Rust have syntax for initializing a struct field with an earlier field?</a>). If I try to shunt sequential initialization with a struct like</p>
  
  <pre><code>struct HoldsVecInRefCellIter&lt;'a&gt; {
      vec_ref: Ref&lt;'a, Vec&lt;i32&gt;&gt;,
      vec_iter: Option&lt;Iter&lt;'a, i32&gt;&gt;,
  }
  
  // ...
  
  impl HoldsVecInRefCell {
      // ...
  
      fn iter(&amp;self) -&gt; HoldsVecInRefCellIter {
          let mut new_iter = HoldsVecInRefCellIter { vec_ref: self.vec_in_refcell.borrow(), vec_iter: None };
          new_iter.vec_iter = new_iter.vec_ref.iter();
          new_iter
      }
  }
  </code></pre>
  
  <p>then I incur a mutable self-borrow of the struct that prevents returning it from <code>iter()</code>. This self-borrowing of a struct can also happen if you try to store a reference to one part of a struct in the struct itself (<a href="https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct?rq=1">Why can&#39;t I store a value and a reference to that value in the same struct?</a>), which would prevent safely moving instances of the struct. By comparison, it seems like a struct like <code>HoldsVecInRefCellIter</code>, if you could complete initialization, would do the correct thing when moved, since all references internally are to data elsewhere that outlives this struct.</p>
  
  <p>There are tricks to avoid creating self-references using <code>Rc</code> (see examples at <a href="https://internals.rust-lang.org/t/self-referencing-structs/418/3" rel="nofollow noreferrer">https://internals.rust-lang.org/t/self-referencing-structs/418/3</a>), but I don't see how these could be applied if you want to store an existing <code>Iterator</code> struct which is implemented to hold a direct reference to the underlying container, not an <code>Rc</code>.</p>
  
  <p>As a Rust newbie coming from C++, this feels like a problem that would come up often ("I have some complex state initialization logic in a block of code, and I want to abstract away that logic and hold the resulting state in a struct for use").</p>
  
  <p><strong>Related Question:</strong> <a href="https://stackoverflow.com/questions/33541492/returning-iterator-of-a-vec-in-a-refcell">Returning iterator of a Vec in a RefCell</a></p>