Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid optional checking when accessing a vector

How can I avoid the optional checking when accessing a Vec?

while !self.stack.is_empty() {
    let top_path;

    if let Some(top) = self.stack.last() {
        top_path = top.to_vec();
    } else {
        panic!("error (but can't happen, becouse the stack can't be empty becouse of the while loop)");
    }

    self.stack.pop();
    self.apply_grammar(top_path);
}

There are 2 problems:

  1. I have to check with the if let... statement (but I know I don't need it)
  2. I need an else panic, because without it top_path could be uninitialized (-> error).

Is it my mistake or is it Rust?

like image 524
boxi Avatar asked Jan 08 '23 09:01

boxi


2 Answers

the irc helped me with the following answer:

while let Some(top) = self.stack.pop() {
    let top_path = top.to_vec();
    let mut is_terminal = self.tree.root.is_terminal( top.to_vec() );

    self.apply_grammar(top_path);
}

and this looks much nicer.

like image 156
boxi Avatar answered Jan 14 '23 18:01

boxi


You could use the Option::unwrap method, which panics on None just like your if let ... else expression:

while !self.stack.is_empty() {
    let top = self.stack.last().unwrap();
    let top_path = top.to_vec();
    self.stack.pop();
    self.apply_grammar(top_path);
}

but in this case it would be even clearer to use a while let block as you mentioned in your own answer.

like image 33
mbrubeck Avatar answered Jan 14 '23 17:01

mbrubeck