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:
if let
... statement (but I know I don't need it)else panic
, because without it top_path
could be uninitialized (-> error).Is it my mistake or is it Rust?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With