Skip to content

Instantly share code, notes, and snippets.

@kriogenia
Last active May 18, 2022 16:05
Show Gist options
  • Save kriogenia/8cdbdf75bec7ece7cc5ce65ffe422183 to your computer and use it in GitHub Desktop.
Save kriogenia/8cdbdf75bec7ece7cc5ce65ffe422183 to your computer and use it in GitHub Desktop.
Generify with compiler errors - Bounded function
fn sum<T>(numbers: &[T]) -> T
where
T: Add<Output = T> + Copy,
{
let mut total = numbers[0];
for i in numbers.into_iter().skip(1) {
total = total + *i;
}
total
}
fn main() {
let ints = vec![23, -4, 3, 10];
let floats = vec![23.0, -4.0, 3.0, 10.0];
let vectors = vec![Vector2D::new(23, -4), Vector2D::new(3, 10), Vector2D::new(1, 1)];
assert_eq!(sum(&ints), 32);
assert_eq!(sum(&floats), 32.0);
assert_eq!(sum(&vectors), Vector2D::new(27, 7));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment