Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 如何在闭包中正确定义生存期_Rust_Lifetime - Fatal编程技术网

Rust 如何在闭包中正确定义生存期

Rust 如何在闭包中正确定义生存期,rust,lifetime,Rust,Lifetime,但我不想把所有权转移到结束。我想要的是,返回的盒式迭代器应该与self和问题的寿命一样长。他们一离开,它就应该离开 我知道这可以通过将克隆的迭代器传递给问题而不是对它的引用来解决,我认为这里不需要它 将移动添加到封口self的类型为&Vec,因此闭包不会拥有向量的所有权,它会捕获向量的引用。闭包应该与发出的和self一样长,而不是相反。生命周期注释不会改变实际的生命周期。仅此而已,添加move将阻止您引用解除分配的向量。不添加move将不允许程序进行编译,因为闭包捕获对函数参数self的引用,该

但我不想把所有权转移到结束。我想要的是,返回的盒式迭代器应该与
self
问题的寿命一样长。他们一离开,它就应该离开

我知道这可以通过将克隆的迭代器传递给
问题
而不是对它的引用来解决,我认为这里不需要它


移动
添加到封口
self
的类型为
&Vec
,因此闭包不会拥有向量的所有权,它会捕获向量的引用。

闭包应该与
发出的
self
一样长,而不是相反。生命周期注释不会改变实际的生命周期。仅此而已,添加
move
将阻止您引用解除分配的向量。不添加
move
将不允许程序进行编译,因为闭包捕获对函数参数
self
的引用,该参数仅存在于函数内部。如果问题出在
self
上,为什么要移动
i
?Is将导致另一个错误。
i
是一个闭包参数,它不受
move
的影响。另一个错误(无法移出借用的内容)与您的问题没有直接关系
into_iter()
尝试使用
*问题
,但无法移出借用的内容。将
&I
替换为
I
以将其删除。
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| {
   |                                         ^