向量 pop() 返回选项

Fel*_* AA 0 types rust vec

我是 Rust 的初学者。我看到pop()向量返回<Option>类型的方法。获取pop()变量值的正确方法是什么?

    let mut queue: Vec<[usize; 2]> = Vec::new();
    queue.push([1, 2]);
    queue.push([3, 4]);

    let coords = queue.pop();
    println!("{}, {}", coords[0], coords[1]);

Run Code Online (Sandbox Code Playgroud)
error[E0608]: cannot index into a value of type `std::option::Option<[usize; 2]>`
  --> src/main.rs:99:24
   |
99 |     println!("{}, {}", coords[0], coords[1]);
   |  
Run Code Online (Sandbox Code Playgroud)

Ry-*_*Ry- 6

如果您知道queue调用pop它时永远不会为空的事实,则可以打开选项:

let coords = queue.pop().unwrap();
Run Code Online (Sandbox Code Playgroud)

否则,您可以对其进行匹配并在这种None情况下执行您需要的任何处理:

let coords = queue.pop().unwrap();
Run Code Online (Sandbox Code Playgroud)

如果您只想在选项为 时做某事,另一种可能性是有用的Some,使用if let

if let Some(coords) = queue.pop() {
    println!("{}, {}", coords[0], coords[1]);
}
Run Code Online (Sandbox Code Playgroud)