ideasman42
ideasman42

Reputation: 48128

What is a less verbose way to repeatedly pop() items from a vector?

When using a vector as a stack (storing states which are pushed and popped).

while stack.len() != 0 {
    let state = stack.pop().unwrap();
    // ... optionally push other states onto the stack.
}

Is there a less verbose way to do this in Rust?

Upvotes: 3

Views: 2889

Answers (2)

allTwentyQuestions
allTwentyQuestions

Reputation: 1240

Just to offer an alternative approach, you can also use the drain method to remove elements and give them to you in an Iterator.

stack.drain(..).map(|element| ...and so on

or

for element in stack.drain(..) {
    //do stuff
}

You can also provide a RangeArgument if you only want to remove a certain range of elements. This can be provided in the form of <start-inclusive>..<end-exclusive>. Both the start and end of the range argument are optional and just default to the start of end of the vector, so calling drain(..) just drains the entire vector, while drain(2..) would leave the first 2 elements in place and just drain the rest.

Upvotes: 4

SpaceManiac
SpaceManiac

Reputation: 535

You can use the fact that pop() returns an Option<T> and match on that using a while let loop:

while let Some(state) = stack.pop() {
    // ... fine to call stack.push() here
}

The while let desugars to something like the following:

loop {
    match stack.pop() {
        Some(state) => {
            // ... fine to call stack.push() here
        }
        _ => break
    }
}

Upvotes: 15

Related Questions