Iterating with offset

Is is possible to do a single iteration run over a full Vec<_> with offset?

Say the vector consists of [1, 2, 3, 4, 5, 6] and I want a loop that gets 4, 5, 6, 1, 2, 3 knowing the index for 4.

I know I can do it in two parts by "skipping" to index 3 and then only allowing to go to index 2 in another loop but wondering if there's a nice way to get this kind of iteration in one go.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=23a87147da606515c55816f2501b9b53

You can use Iterator::cycle() and Iterator::take().

1 Like

Here's a slightly different way to do it:

let (front, back) = v.split_at(3);
for element in back.iter().chain(front) { /* loop */ }
4 Likes