I am really new in rust, and while going through the rustlings exercises I found something I do not fully understand regarding stacked Options.
Given the following code:
let vector = vec![Some(24), None, Some(42)];
let mut iter = vector.iter();
while let Some(Some(number)) = iter.next() {
println!("Number: {}", number);
}
I would expect to see the following output:
Number: 24
Number: 42
But I guess as soon as rust encounters the None
, the while loop exits, only printing the 24
What would be the most idiomatic rust code to iterate and unwrap optional values? The closest that I got would look something like this:
let mut iter = vector.iter();
while let Some(iterNext) = iter.next() {
if let Some(num) = iterNext {
println!("Number: {}", num);
}
}
Or it could also be done by checking the existence in a for loop:
for opt in &vector {
if opt.is_some() {
println!("Number: {}", opt.unwrap());
}
}
Some(None)
, thewhile
loop breaks. What is "more idiomatic" is more or less a matter of opinion, but I would definitely prefer theif let
instead of theis_some
/unwrap
version. The whole point ofif let
is so that you can avoid manually checking / unwrapping the option. – Jesper