Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way to pop the last N elements in a mutable Vec?

Tags:

rust

I am contributing Rust code to RosettaCode to both learn Rust and contribute to the Rust community at the same time. What is the best idiomatic way to pop the last n elements in a mutable Vec?

Here's roughly what I have written but I'm wanting to see if there's a better way:

fn main() {
    let mut nums: Vec<u32> = Vec::new();
    nums.push(1);
    nums.push(2);
    nums.push(3);
    nums.push(4);
    nums.push(5);

    let n = 2;
    for _ in 0..n {
        nums.pop();
    }

    for e in nums {
        println!("{}", e)
    }
}

(Playground link)

like image 828
bitloner Avatar asked Mar 09 '15 21:03

bitloner


1 Answers

I'd recommend using Vec::truncate:

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

    let n = 2;
    let final_length = nums.len().saturating_sub(n);
    nums.truncate(final_length);

    println!("{:?}", nums);
}

Additionally, I

  • used saturating_sub to handle the case where there aren't N elements in the vector
  • used vec![] to construct the vector of numbers easily
  • printed out the entire vector in one go

Normally when you "pop" something, you want to have those values. If you want the values in another vector, you can use Vec::split_off:

let tail = nums.split_off(final_length);

If you want access to the elements but do not want to create a whole new vector, you can use Vec::drain:

for i in nums.drain(final_length..) {
    println!("{}", i)
}
like image 52
Shepmaster Avatar answered Sep 28 '22 00:09

Shepmaster