Look back during iterating array I have an array (or string) to parse and I want to examine each element sequentially. This is a perfect case for the iterators / consumers that Rust offers.

The problem arises when I have to access previously parsed data during iteration. For example, I need to subtract the item that was 5 places before the current item.

The best way I know to achieve this using idiomatic Rust is a sliding window Vec that keeps track of the items previously seen, all of which happens inside a fold operation.

A working code extract looks like the following:

fn main() {
   let string = "111222023333"; // the string to parse  
   let str_iter = string.trim_left().trim_right().chars();
   let mut last = 1 as usize;
   let mut digit = 0 as usize;
   let mut window: Vec&lt;usize&gt; = Vec::new();
   let target = 5;
   str_iter.fold(1, |mut val, c| {
      digit = c.to_digit(10).unwrap() as usize;
      window.push(digit);
      if window.len() &gt; target 
        {last = window.remove(0);} 
      if digit == 0 
        {val -= last;}
      val
   });
}


I don't really like this as I have to use a Vec to store the values of size target; I could just use indexes like I would in C/C++ but that again feels a bit wrong and not idiomatic at all.

Any ideas on how to idiomatic achieve this without using an additional Vec?
.trim_left().trim_right() is just .trim().
You might as well inline str_iter, since you only use it in one place. At least move it closer to the use-point.
Folds aren't the idiomatic loop primitive in Rust. In this case it would be much nicer to just use for.


This improves compiler analysis, and you find out that digit's initial assignment isn't getting read. You don't need digit outside the loop at all, and thus it doesn't even need to be mutable.

You're using too many type annotations. The one as usize after to_digit is enough, and even if you did need to annotate the others you should use let last: usize = 1 or let last = 1usize. Similarly, let the Vec's type parameter be inferred.
Your brace formatting is not Rusty.
Instead of dealing with window, just run two zipped offset parallel iterators. Indices work fine, too, and aren't unidiomatic: clearer, efficient code is always idiomatic.