Search code examples
rustvector

How to get value from Vec::pop()?


I see pop() method of vector returns an Option type. What the right way to get pop() value to a variable?

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]);
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]);
   |  

Solution

  • If you know for a fact that queue will never be empty when you call pop on it, you can unwrap the option:

    let coords = queue.pop().unwrap();
    

    Otherwise, you can match on it and do whatever handling you need to in the None case:

    let coords = match queue.pop() {
        Some(top) => top,
        None => {
            // … handling …
        }
    };
    

    Another possibility, useful if you only want to do something when the option is Some, is use if let:

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