Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created February 6, 2024 19:14
Show Gist options
  • Save fancellu/8a66f6cd3141ff61d69ed64e2f3046dc to your computer and use it in GitHub Desktop.
Save fancellu/8a66f6cd3141ff61d69ed64e2f3046dc to your computer and use it in GitHub Desktop.
Sum up a vector of optional numbers
use std::iter::Sum;
fn sum_with_missing<T: Sum + Copy>(vec: &Vec<Option<T>>) -> T {
vec.into_iter().filter_map(|x| *x).sum()
}
fn main() {
let mut v = vec![Some(1), Some(2), Some(3), None, Some(5)];
println!("{}", sum_with_missing(&v));
v.push(Some(10));
println!("{}", sum_with_missing(&v));
let mut f = vec![Some(1.0), Some(2.0), Some(3.0), None, Some(5.1)];
println!("{}", sum_with_missing(&f));
}
@fancellu
Copy link
Author

fancellu commented Feb 6, 2024

Outputs

11
21
11.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment