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

后端 未结 3 1284
清歌不尽
清歌不尽 2021-01-17 11:42

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

3条回答
  •  误落风尘
    2021-01-17 12:42

    You should take a look at the Vec::truncate function from the standard library, that can do this for you.

    (playground)

    fn main() {
        let mut nums: Vec = Vec::new();
        nums.push(1);
        nums.push(2);
        nums.push(3);
        nums.push(4);
        nums.push(5);
    
        let n = 2;
        let new_len = nums.len() - n;
        nums.truncate(new_len);
    
        for e in nums {
            println!("{}", e)
        }
    }
    

提交回复
热议问题