JustCoding
JustCoding

Reputation: 408

Is there something like a rolling Array index?

Following mwe:

let months = ["January", "February", "March", "April", "May", "June", "July",
              "August", "September", "October", "November", "December"];
println!("Seasons are:\n\tSpring ({:?})\n\tSummer ({:?})\n\tFall ({:?})\n\tWinter ({:?})",
        &months[2..5],
        &months[5..8],
        &months[8..11],
        [&months[11],&months[0],&months[1]]
    )

The issue here is, that the last season is comprised of the last value of the array and the first two. For this example, I can add them manually. But in practice, with more values, this won't be viable.

Since this is a fixed (immutable) array, is there a way of something like rolling index? For example something like

[&months[11]..+3]

or

[&months[11], &months[0..2]]

What is the most elegant way of handling such a case?

Upvotes: 1

Views: 114

Answers (1)

Jmb
Jmb

Reputation: 23319

A slice is a contiguous piece of memory, so it's impossible to take a slice that wraps around the way you want since the corresponding elements are not contiguous. Depending on what you really want to do, you might be able to work with iterators and chain:

months[11..].iter().chain (months[..3].iter())

or simply with a couple of loops:

print!("Winter ([");
for m in months[11..] { // In this case, you would probably put `months[11]` directly in the first `print`
    print!("{:?}, ", m);
}
for m in months[..3] {
    print!("{:?}, ", m);
}
println!("])");

Upvotes: 1

Related Questions