Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Vector with optional values - None or out of range?

  • get

  • is_none

  • is_some

  • TODO

  • If we have a vector that some of the elements can be None then the other elements must be Some-values and the whole thing must be defined using Option.

  • If we try to access an element in a vector that is out of range we get a run-time panic.

  • In order to avoid such panic we either need to check if our index is in range or we can use the get method.

  • We can use the get method to access the element. It will return None if the index was out of range.

  • Then the question arise, how do we know if the value was out of range or if it was in the range but the value was None?

fn main() {
    let numbers_real: Vec<Option<i32>> = vec![Some(3), None];
    println!("{:?}", numbers_real);

    println!("{:?}", numbers_real[1]); // None
    println!("{:?}", numbers_real.get(1)); // Some(None)
                                           // println!("{:?}", numbers_real[17]); // panic: index out of bounds: the len is 2 but the index is 17
    println!("{:?}", numbers_real.get(17)); // None    - out of range!
    println!();

    println!("{:?}", numbers_real.get(1).is_none());
    println!("{:?}", numbers_real.get(17).is_none()); // out of range!
    println!();

    println!("{:?}", numbers_real.get(1).is_some());
    println!("{:?}", numbers_real.get(17).is_some()); // out of range!
    println!();
}
[Some(3), None]
None
Some(None)
None

false
true

true
false