# Idiomatic way to get second last, third last, fourth last elements of a vector/array/slice

**URL:** <https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495>\
**Category:** help\
**Created:** [May 7, 2021, 11:03am UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495 "2021-05-07T11:03:51Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![KSXGitHub](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/ksxgithub/32/10388_2.png) [@KSXGitHub](https://users.rust-lang.org/u/KSXGitHub)\
**Post date:** [May 7, 2021, 11:03am UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/1 "2021-05-07T11:03:52Z")

</div>

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 `Option`s.

I don't require a generic solution, only second, third, and fourth last.

Lastly, the code shouldn't panic.

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/quinedot/32/17693_2.png) [@quinedot](https://users.rust-lang.org/u/quinedot)\
**Post date:** [May 7, 2021, 11:11am UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/2 "2021-05-07T11:11:49Z")

</div>

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](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=19d680144adb86c1664a725b649f6833) for one combination (all of those specifically at once, by reference, might panic):

```rust
let s = &v[v.len() - 4 .. v.len() - 1];

```

---

<div class="post-metadata">

**Author:** ![KSXGitHub](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/ksxgithub/32/10388_2.png) [@KSXGitHub](https://users.rust-lang.org/u/KSXGitHub)\
**Post date:** [May 7, 2021, 11:15am UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/3 "2021-05-07T11:15:04Z")

</div>

I have updated my question.

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/quinedot/32/17693_2.png) [@quinedot](https://users.rust-lang.org/u/quinedot)\
**Post date:** [May 7, 2021, 11:23am UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/4 "2021-05-07T11:23:30Z")

</div>

[Again going for brevity:](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5ca8fe770f2536c981fee3798dc7321d)

```rust
// 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]);

```

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [May 7, 2021, 11:26am UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/5 "2021-05-07T11:26:14Z")

</div>

```rust
let a = vec.get(vec.len().wrapping_sub(2));
let b = vec.get(vec.len().wrapping_sub(3));
let c = vec.get(vec.len().wrapping_sub(4));

```

If the length is too small, this will wrap around and the index will be far-far out of range, so `get` will return `None`.

---

<div class="post-metadata">

**Author:** ![trentj](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/trentj/32/5690_2.png) [@trentj](https://users.rust-lang.org/u/trentj)\
**Post date:** [May 7, 2021, 11:30am UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/6 "2021-05-07T11:30:54Z")

</div>

```
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 `Some`s 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.)

---

<div class="post-metadata">

**Author:** ![Hyeonu](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/hyeonu/32/7970_2.png) [@Hyeonu](https://users.rust-lang.org/u/Hyeonu)\
**Post date:** [May 7, 2021, 11:49am UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/7 "2021-05-07T11:49:10Z")

</div>

Since OP mentioned slices not iterators, pattern matching would be the shortest I guess.

```rust
let (a, b, c) = match &arr[..] {
    [.., a, b, c, _] => (a, b, c),
    _ => panic!("array shorter than 4"),
};

```

> **[Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8976b292814a528a1b959f98020a289e)**
>
> A browser interface to the Rust compiler to experiment with the language

---

<div class="post-metadata">

**Author:** ![cliff](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cliff/32/689_2.png) [@cliff](https://users.rust-lang.org/u/cliff)\
**Post date:** [May 7, 2021, 12:28pm UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/8 "2021-05-07T12:28:23Z")

</div>

```rust
let len = arr.len();
let results = arr[len.saturating_sub(4)..len.saturating_sub(1)];

```

Another approach that doesn't use iterators.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/scottmcm/32/4286_2.png) [@scottmcm](https://users.rust-lang.org/u/scottmcm)\
**Post date:** [May 7, 2021, 7:23pm UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/9 "2021-05-07T19:23:24Z")

</div>

EDIT: Skip this post -- steffahn points out in the post below that it's not meeting the requirements.

With [rev\_slice — Rust library // Lib.rs](https://lib.rs/crates/rev_slice),

```rust
if let [c, b, a] = v.rev()[1..4].rev() {

```

(But really I'd vote for the pattern in [Hyeonu's solution](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/7).)

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/steffahn/32/47569_2.png) [@steffahn](https://users.rust-lang.org/u/steffahn)\
**Post date:** [May 7, 2021, 7:57pm UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/10 "2021-05-07T19:57:38Z")

</div>

> [@Hyeonu](#):
>
> Since OP mentioned slices not iterators, pattern matching would be the shortest I guess.
> 
> ```rust
> let (a, b, c) = match &arr[..] {
> [.., a, b, c, _] => (a, b, c),
> _ => panic!("array shorter than 4"),
> };
> 
> ```

but this doesn’t match the requirement of

> [@KSXGitHub](#):
>
> 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 `Option` s.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/scottmcm/32/4286_2.png) [@scottmcm](https://users.rust-lang.org/u/scottmcm)\
**Post date:** [May 7, 2021, 9:20pm UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/11 "2021-05-07T21:20:45Z")

</div>

> [@trentj](#):
>
> Be careful generalizing this to other iterators

I think that means the recommendation should just be

```rust
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.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [August 5, 2021, 9:21pm UTC](https://users.rust-lang.org/t/idiomatic-way-to-get-second-last-third-last-fourth-last-elements-of-a-vector-array-slice/59495/12 "2021-08-05T21:21:06Z")

</div>

Closed on August 5, 2021, 9:21pm UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
