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
Nonethen the other elements must beSome-values and the whole thing must be defined usingOption. -
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
getmethod. -
We can use the
getmethod to access the element. It will returnNoneif 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