Skip to content

Instantly share code, notes, and snippets.

Created February 6, 2024 19:14
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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));
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));
Copy link

fancellu commented Feb 6, 2024



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