Skip to content

Instantly share code, notes, and snippets.

@cppio
Created April 14, 2020 17:45
Show Gist options
  • Select an option

  • Save cppio/d93cc6fc5c7b459b2c8b7c2e2b7db88c to your computer and use it in GitHub Desktop.

Select an option

Save cppio/d93cc6fc5c7b459b2c8b7c2e2b7db88c to your computer and use it in GitHub Desktop.
Simple snippet showing how to skip the last item in an iterator.
fn main() {
let x = [0, 1, 2];
let y: Vec<_> = x
.iter()
.scan(None, |prev, i| Some(prev.replace(i)))
.flatten()
.collect();
println!("x = {:?}", x); // x = [0, 1, 2]
println!("y = {:?}", y); // y = [0, 1]
}
@cppio
Copy link
Author

cppio commented Apr 14, 2020

This works by transforming

[0, 1, 2]

using scan() into

[None, Some(0), Some(1)]

and then calling flatten() to get

[0, 1]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment