What is the best way to get second last, third last, and fourth last elements of a vector/array/slice of unknown length? The fewer lines of code the better.
There are cases where the second last exists but not the third last and the fourth last, so I prefer to get them separately, as Options.
I don't require a generic solution, only second, third, and fourth last.
Those specifically or from the end more generally? One of those arbitrarily, all at once, sequentially? By reference, cloned, or owning? Graceful errors or panics on short inputs?
Here's a one liner for one combination (all of those specifically at once, by reference, might panic):
// Is an `Option<_>`, replace 3 with 1 for last, 2 for penultimate, etc.
// Will still panic if you use 0 though
let maybe_third_last = v.len().checked_sub(3).map(|i| v[i]);
let mut rev = xs.iter().rev();
let (_, second, third, fourth) = (rev.next(), rev.next(), rev.next(), rev.next());
(Be careful generalizing this to other iterators, because not all iterators will continue to yield None after the first time; so with an arbitrary iterator you might get Somes in third and fourth even if second is a None. But Rev<slice::Iter> is a FusedIterator, so it is guaranteed to work the way you want.)
I think that means the recommendation should just be
let mut rev = xs.iter().rev().fuse();
let (_, second, third, fourth) = (rev.next(), rev.next(), rev.next(), rev.next());
even for vectors and slices, because there's no overhead for the .fuse() on them (thanks to specialization and layout optimization) and that way it will continue to work correctly if a non-fused iterator somehow shows up -- not to mention that it will emphasize to the reader that you're intending to use this behaviour.