2017-09-29 4 views
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() 
} 

エラーメッセージは、私はI::Itemi32への参照(&i32)であるが、f64::fromのみ値に対して実施されることを理解

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` 

あります。どのようにしてこれをコンパイルするのですか?

+2

我々はハードツー続く質問で悪いフォーマット、過度に大きいポストの*ロット*を取得します。私はこの質問がそれらのどれでもなく、大きな努力を示していることを認識したいと思います! – Shepmaster

答えて

1

イテレータに変換できるものはすべて受け入れるので、イテレータの各アイテムを逆参照されたフォームに変換できます。ここでは最も簡単な方法は、Iterator::clonedを使用することです:

assert_eq!(vec![0.0, 1.0, 2.0], int_to_float([0, 1, 2].iter().cloned())); 
関連する問題