How to create descending slice

0..10 makes a slice in increasing order, but reverse order 10..0 is not legal.
How to create a slice in decreasing order?

(0..10).rev()

If you want either one, that's a bit silly, but you need to unify their types with an abstraction like https://lib.rs/crates/either

One thing to note here is that you're calling this a "slice" but a slice is continuous data [T]. What you're referring to is most likely either a Range like @kornel was talking about or slicing data, where you do something like the following:

let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15];
let slice: &[usize] = &v[0..10];

Which is also called indexing. Here you cannot apply some magic to get a &[usize] back in reverse because that would mean rearranging the data or producing it in an iterator like way. Which leads me to iterators: you can use something like so:

let (lower, upper) = (0, 10);
for i in v.iter().take(upper).skip(lower) {
    println!("{:?}", I);
}
2 Likes

<shameless plug>

You could also use something like this to make it look like a backwards slice

</shameless plug>

4 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.