While if let Some(Enum(x)) = Vec::pop()?

I've noticed some strangeness when using selective enum variant if let in combination with a while loop using Vec::pop().

See this example

How come it ends with one record??

while let will continue as long as the pattern matches. You popped both InnerTwo, nothing weird there. Then you pop a InnerOne but it doesn't match so the loop stops.
All that remains is the last value.
If you want to pop everything you can "loosen" the pattern. playground

1 Like

So what actually happens, is:

  1. pop last value from vec.
  2. see if the pattern matches
  3. if it matches, execute the loop body and then go to 1. else go past the loop.

So your code does the following:

pop 4th value
matches pattern => match => executes loop.
pop 3rd value
matches pattern => match => executes loop
pop 2nd value
matches pattern => doesn't match => jump past loop
prints remaining values and len of vec, which is now only the first value, not the second value as well, since the second value has been popped.

1 Like