2017-10-05 15 views
2
impl Rate for Vec<VolumeRanged> { 
    fn costs<'a, I>(&'a self, issues: &I, period: u32) -> Box<'a + Iterator<Item = f32>> 
    where 
     I: IntoIterator<Item=f32>, 
     I::IntoIter: 'a 
    { 
     fn issue_cost(issue: f32, percentage: f32, constant: f32, max: f32) -> f32 { 
      let r = issue * percentage/100.0 + constant; 
      match r.partial_cmp(&max) { 
       Some(Less) => r, 
       _ => max 
      } 
     } 
     Box::new(issues.into_iter().map(|i| { 
      let (pr, nr) = pairwise(self) 
         .find(|&(_, n)| in_range(&i, &n.range)) 
         .expect("No range found"); 
      issue_cost(
       i, 
       nr.percentage, 
       pr.map_or(0.0, |x| x.max), 
       nr.max, 
      ) 
     })) 
    } 
} 

錆が 閉鎖に適切に寿命を定義する方法を

error[E0373]: closure may outlive the current function, but it borrows `self`, which is owned by the current function 
    --> src/main.rs:43:41 
    | 
43 |   Box::new(issues.into_iter().map(|i| { 
    |           ^^^ may outlive borrowed value `self` 
44 |    let (pr, nr) = pairwise(self) 
    |          ---- `self` is borrowed here 
    | 
help: to force the closure to take ownership of `self` (and any other referenced variables), use the `move` keyword 
    | 
43 |   Box::new(issues.into_iter().map(move |i| { 
    |          ^

を言っているしかし、私は閉鎖に所有権を移動する必要はありません。私が望むのは、返されたボックスイテレータは、 selfissuesの両方の長さで生きていなければならないということです。彼らが離れるとすぐに、それはなくなるはずです。

これは、複製されたイテレータを参照の代わりにissuesに渡すことで解決できることを知っていますが、ここでは必要ないと思います。

playground

答えて

1

閉鎖にmoveを追加します。 selfのタイプは&Vec<VolumeRanged>なので、クロージャーはベクトルの所有権を取得しません。ベクターへの参照を取得します。

+0

私はすでに私がそれをしたくない理由を言ったと思います。 – user1685095

+0

「問題」と「自己」の間に生きていなければならない閉鎖です。 – user1685095

+0

ライフタイムアノテーションは実際のライフタイムを変更しません。 'move'を追加すると、割り当てられていないベクトルへの参照ができなくなります。クロージャが関数内でのみ存在する関数パラメータ 'self'を参照するため、' move'を追加しないとプログラムをコンパイルできません。 – red75prime

関連する問題