What is the idiomatic way to get the tail of a vector?

Viewed 1686

I have this:

let stuff = vec![1, 2, 3];
let tail = stuff[1..].iter().collect::<Vec<_>>();
println!("Hello, world! {:?}", tail);

I was wondering if this is idiomatic, as I find the call to iter and then to collect verbose.

3 Answers

You don't need to actually create a new vector to print the values. Just use a slice.

let tail = &stuff[1..];
println!("Hello, world! {:?}", tail);

playground

You may want to use [T]::split_first, which returns an Option rather than panicking. This means you can choose what to do if stuff is empty.

if let Some((_, tail)) = stuff.split_first() {
    println!("Hello, world! {:?}", tail);
}

let (_, tail) = stuff.split_first().unwrap() would be equivalent to let tail = &stuff[1..] (but with a slightly different panic message).

See also

Since slices (and therefor Vec) implement DoubleEndedIterator, you can take an iterator (1,2,3,4), reverse it (4,3,2,1), take a number of elements (4,3,2) and reverse it again. This might seem strange at first, yet no manual slicing needs to be done and no special cases need to be considered:

fn main() {
    let v = vec![1,2,3,4,5];

    // Will print the last 3 elements in order; "3,4,5"
    for x in v.iter().rev().take(3).rev() {
        println!("{}", x);
    }
}
Related