Why does Iterator :: take_while get ownership of the iterator?

It seemed strange to me that Iterator::take_while gets ownership of the iterator. It looks like a useful function allows you to take the first elements of x that satisfy some function, but still leave the rest of the elements available in the original iterator.

I understand that this is incompatible with the lazy take_while implementation, but still useful. Was it just not useful enough for inclusion in the standard library, or is there some other problem that I don't see?

+7
rust
source share
1 answer

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 .

+9
source share

All Articles