我想将任何数字类型的列表转换为浮点列表。以下代码无法编译:
#[cfg(test)]
mod tests {
#[test]
fn test_int_to_float() {
use super::int_to_float;
assert_eq!(vec![0.0, 1.0, 2.0], int_to_float(&[0, 1, 2]));
}
}
pub fn int_to_float<I>(xs: I) -> Vec<f64>
where
I: IntoIterator,
f64: From<I::Item>,
{
xs.into_iter().map(f64::from).collect()
}
错误消息是
error[E0277]: the trait bound `f64: std::convert::From<&{integer}>` is not satisfied
--> src/main.rs:6:41
|
6 | assert_eq!(vec![0.0, 1.0, 2.0], int_to_float(&[0, 1, 2]));
| ^^^^^^^^^^^^ the trait `std::convert::From<&{integer}>` is not implemented for `f64`
|
= help: the following implementations were found:
<f64 as std::convert::From<i8>>
<f64 as std::convert::From<i16>>
<f64 as std::convert::From<f32>>
<f64 as std::convert::From<u16>>
and 3 others
= note: required by `int_to_float`
我了解I::Item
是对i32
(&i32
)的引用,但f64::from
仅针对值实施。如何编译?
答案 0 :(得分:1)
因为您接受任何可以转换为迭代器的东西,您可以将迭代器中的每个项目转换为取消引用的形式。最简单的方法是使用Iterator::cloned
:
assert_eq!(vec![0.0, 1.0, 2.0], int_to_float([0, 1, 2].iter().cloned()));