Created
November 7, 2021 09:45
-
-
Save JosephTLyons/2362e6cdf0963d32cc33c086dfb6c448 to your computer and use it in GitHub Desktop.
A few examples illustrating a few ways to iterate over `Results` in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let items: [Result<i32, &str>; 4] = [Ok(1), Ok(2), Err("Missing Value"), Ok(3)]; | |
// 1 | |
let items_result: Result<Vec<_>, _> = items.into_iter().collect(); | |
match items_result { | |
Ok(items) => { | |
for item in items { | |
println!("{}", item); | |
} | |
} | |
Err(error) => println!("{}", error), | |
} | |
// 2 | |
let items: Vec<i32> = items | |
.iter() | |
.filter_map(|value_result| value_result.ok()) | |
.collect(); | |
for item in items { | |
println!("{}", item); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment