"From trait"仅适用于值,但我有引用。

3
我希望将任何数字类型的列表转换为浮点数列表。以下代码无法编译:
#[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)的引用,但f64::from仅适用于值。如何使其编译通过?


2
我们收到了很多格式不良、过于庞大且难以理解的问题帖子。我想要承认这个问题不属于那些问题之列,而是展现出极大的努力! - Shepmaster
1个回答

1
因为您接受可以转换为迭代器的任何内容,所以可以将迭代器中的每个项目转换为取消引用的形式。在这里最简单的方法是使用 Iterator::cloned
assert_eq!(vec![0.0, 1.0, 2.0], int_to_float([0, 1, 2].iter().cloned()));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接