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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…