3

I am beginner in rust. I see pop() method of vector returns <Option> type. What the right way to get pop() value to 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]);
   |  
Herohtar
  • 5,347
  • 4
  • 31
  • 41
Fel AA
  • 303
  • 5
  • 16

1 Answers1

14

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]);
}
Jesper
  • 202,709
  • 46
  • 318
  • 350
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Thanks! `.unwrap()` is good solution for my case. But now I have other problem, because `coords` variable have type `[usize, _]`, but I need `[usize, 2]`. I get `mismatched types` error. Could you help me with this? – Fel AA Oct 05 '20 at 09:53
  • @FelAA: Hm, I’d think it’d be `[usize; 2]`. Can you edit the error message into your question? – Ry- Oct 05 '20 at 09:58
  • This is strange, but I can not reproduce this error after some changes :) I think it was wrong error message of IDE, because actually I had error with `usize` and `u8` mismatching. Anyway, thank you very much! – Fel AA Oct 05 '20 at 10:08
  • Is there a reason behind why `queue.pop()` would return an Option type? – CrazyVideoGamer Apr 29 '21 at 17:05
  • @CrazyVideoGamer: It can’t remove and return a value from the queue if the queue is empty. – Ry- May 18 '22 at 21:57