Conditionally popping from a vec

Newbie here!

Suppose I have a mutable vec and if it contains any more than a certain number of elements, I would like to pop the last element and use it, otherwise I want to do something else. I can easily handle this with an unwrap() or an unreachable!(), but both feel weird since I know the vec can't possibly be empty, having just checked the length. Is there a better way to express this? Currently I am doing the following:

if my_vec.len() > 5 {
    match my_vec.pop() {
        Some(n) => do_something(n), 
        None => unreachable!(),
    //do something else

I would just unwrap() that.

1 Like

I like to use expect() in cases like these where I know something will exist but unwrap feels wrong.

You can do

if let Some(n) = my_vec.pop() {




do_something(my_vec.remove(vec.len() - 1));

and those are all the variations I could think of to help clean things up.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.