All iterator adapters take the original iterator in value for efficiency. If you want to keep access to the original iterator, you can use by_ref . This introduces one level of indirection, but the programmer chooses the possibility of additional work when this function is required:
fn main() { let v = [1, 2, 3, 4, 5, 6, 7, 8]; let mut i1 = v.iter(); for z in i1.by_ref().take_while(|&&v| v < 4) { println!("Take While: {}", z); } for z in i1 { println!("Rest: {}", z); } }
Does it have a conclusion
Take While: 1 Take While: 2 Take While: 3 Rest: 5 Rest: 6 Rest: 7 Rest: 8
Did you notice that 4 missing? This is because once take_while selects a value and decides not to use it, it has nowhere to "return it". Going back would require choosing more memory and slowness than is always necessary.
I used itertools crate to handle such cases, in particular take_while_ref .
Shepmaster
source share