Skip to content

Instantly share code, notes, and snippets.

@JosephTLyons
Created November 7, 2021 09:45
Show Gist options
  • Save JosephTLyons/2362e6cdf0963d32cc33c086dfb6c448 to your computer and use it in GitHub Desktop.
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
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