Hello,
as an exercise, I am trying to write a generic sum function. Just like for
can iterate over anything that implements IntoIterator
, I would like my function to also accept anything that can be turned into an iterator.
I have the following, which works:
use std::ops::Add;
fn sum<T, I>(iterable: I) -> T
where
I: IntoIterator<Item = T>,
T: Add<Output = T> + Default
{
let mut result = T::default();
for elem in iterable {
result = result + elem;
}
result
}
fn main() {
let something = vec![0, 2, 1];
println!("{}", sum(something));
}
But this doesn't work when the calling line is changed to
println!("{}", sum(&something));
I managed to modify the sum function so that it works for a reference
fn sum_ref<'a, T, I>(iterable: I) -> T
where
I: IntoIterator<Item = &'a T>,
T: 'a + Add<Output = T> + Default + Copy,
{
let mut result = T::default();
for elem in iterable {
result = result + *elem;
}
result
}
but now it no longer works for a non-reference...
Is there a way to have a single function which works in both cases?