I've looked around Google and SO for an answer to this, but I couldn't find one. I'm trying to understand iterators, so I can use them as parameters rather than taking a Vec or some other concrete collection. In this example, I'm using floats.
I know sums can be computed using the standard library. I'm looking to understand how to use IntoIterators using this alternate implementation.
fn sample_size_sum<T, I>(values: &mut I, is_sample: bool) -> (u32, T)
where I: IntoIterator<Item = T> + std::iter::FromIterator<T>, T: num::Float + std::ops::AddAssign + Copy
{
let mut it = values.into_iter();
let mut sum: T = num::Float::nan();
let mut sample_size = 0;
let mut first = true;
while let Some(value) = it.next()
{
if !value.is_nan()
{
sample_size += 1;
if first
{
sum = value;
first = false;
}
else
{
sum += value;
}
}
}
if is_sample && sample_size > 0
{
sample_size -= 1;
}
return (sample_size, sum);
}
fn main()
{
let mut numbers = vec![1.0, 2.0, 3.0, std::f64::NAN, 5.0];
let (sample_size, sum) = sample_size_sum(&mut numbers, false);
}
The compiler returns the following on the call to into_iter().
cannot move out of `*values` which is behind a mutable reference(E0507)
Does this mean the Vec object owns the iterator which is being moved to my function's scope? I've seen some examples of lifetime syntax which tied the lifetime of parameters and return values together, but I'm not sure what to do with this local variable. I'd appreciate some help.