2017-10-05 46 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'将会阻止您引用已释放的向量,就这些了。不添加'move'将不允许程序编译,因为闭包捕获了函数参数'self'的引用,它只存在于一个函数中。 – red75prime