Created
February 6, 2024 19:14
-
-
Save fancellu/8a66f6cd3141ff61d69ed64e2f3046dc to your computer and use it in GitHub Desktop.
Sum up a vector of optional numbers
This file contains 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
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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Outputs
11
21
11.1