访问矢量时避免可选的检查

box*_*oxi 3 optional rust

访问时如何避免可选的检查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);
}
Run Code Online (Sandbox Code Playgroud)

有两个问题:

  1. 我必须查看if let...声明(但我知道我不需要它)
  2. 我需要一个else panic,因为没有它top_path可能是未初始化的( - >错误).

这是我的错误还是Rust?

box*_*oxi 6

irc帮助我得到以下答案:

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);
}
Run Code Online (Sandbox Code Playgroud)

这看起来好多了.thx <3