Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

rust - How do I create a function that accepts an iterator of i32s as either values or references and sums them?

Is there a way to have a single function that accepts an iterator to either values or references? If not, is there a way to rewrite one or both of the tests so that they can both call the same mean function?

#[cfg(test)]
mod tests {
    #[test]
    fn test_mean_of_references() {
        let array = [47, 48, 49];
        assert_eq!(47.5, super::mean_of_references(46, &mut array.iter()));
    }

    #[test]
    fn test_mean_of_values() {
        let array = [46, 47, 48];
        let mut iter = array.iter().map(|x| x + 1);
        assert_eq!(47.5, super::mean_of_values(46, &mut iter));
    }
}

pub fn mean_of_values(x: i32, xs: &mut std::iter::Iterator<Item = i32>) -> f64 {
    let (sum, len) = xs.fold((x, 1), |acc, x| (acc.0 + x, acc.1 + 1));
    f64::from(sum) / f64::from(len)
}

pub fn mean_of_references(x: i32, xs: &mut std::iter::Iterator<Item = &i32>) -> f64 {
    let (sum, len) = xs.fold((x, 1), |acc, x| (acc.0 + x, acc.1 + 1));
    f64::from(sum) / f64::from(len)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to declare that you will take a generic iterator that yields values which can be added to an i32 and will return an i32:

use std::ops::Add;

pub fn mean<I>(x: i32, xs: I) -> f64
where
    I: IntoIterator,
    i32: Add<I::Item, Output = i32>,
{
    let (sum, len) = xs.into_iter().fold((x, 1u32), |acc, x| (acc.0 + x, acc.1 + 1));
    f64::from(sum) / f64::from(len)
}

For enhanced fun, it takes in something implementing IntoIterator, which means that call sites can be changed to

super::mean(46, &array)
super::mean(46, iter)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...