title: How can I iterate over a delimited string, accumulating state from previous iterations without explicitly tracking the state?
body: <p>I want to produce an iterator over a delimited string such that each substring separated by the delimiter is returned on each iteration with the substring from the previous iteration, including the delimiter.</p>
  
  <p>For example, given the string <code>"ab:cde:fg"</code>, the iterator should return the following:</p>
  
  <ol>
  <li><code>"ab"</code></li>
  <li><code>"ab:cde"</code></li>
  <li><code>"ab:cde:fg"</code></li>
  </ol>
  
  <p><strong>Simple Solution</strong></p>
  
  <p>A simple solution is to just iterate over collection returned from splitting on the delimiter, keeping track of the previous path:</p>
  
  <pre class="lang-rust prettyprint-override"><code>let mut state = String::new();
  for part in "ab:cde:fg".split(':') {
      if !state.is_empty() {
          state.push_str(":");
      }
      state.push_str(part);
      dbg!(&amp;state);
  }
  </code></pre>
  
  <p>The downside here is the need to explicitly keep track of the state with an extra mutable variable.</p>
  
  <p><strong>Using <code>scan</code></strong></p>
  
  <p>I thought <code>scan</code> could be used to hide the state:</p>
  
  <pre class="lang-rust prettyprint-override"><code>    "ab:cde:fg"
          .split(":")
          .scan(String::new(), |state, x| {
              if !state.is_empty() {
                  state.push_str(":");
              }
              state.push_str(x);
              Some(&amp;state)
          })
          .for_each(|x| { dbg!(x); });
  </code></pre>
  
  <p>However, this fails with the error:</p>
  
  <blockquote>
    <p>cannot infer an appropriate lifetime for borrow expression due to conflicting requirements</p>
  </blockquote>
  
  <p>What is the problem with the <code>scan</code> version and how can it be fixed?</p>