Created
May 18, 2022 15:40
-
-
Save kriogenia/7f2bf4c158769d2f258fe2ed02140d2d to your computer and use it in GitHub Desktop.
Generify with compiler errors - Adding starting with zero
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
fn sum<T>(numbers: &[T]) -> T | |
where | |
T: Add<Output = T> + Copy + Zero, | |
{ | |
let mut total: T = T::zero(); | |
for i in numbers.into_iter() { | |
total = total + *i; | |
} | |
total | |
} | |
fn main() { | |
let ints = vec![23, -4, 3, 10]; | |
let floats = vec![23.0, -4.0, 3.0, 10.0]; | |
assert_eq!(sum(&ints), 32); | |
assert_eq!(sum(&floats), 32.0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment