在闭包内通过引用保存值

问题描述 投票:1回答:1

鉴于以下示例,我想在我的闭包内通过引用使用z

struct Foo<'a> {
  x: Box<dyn Fn() + Send + Sync + 'a>,
  y: Box<dyn Fn() + Send + Sync + 'a>,
}

impl<'a> Foo<'a> {
  fn new(z: &'a str) -> Foo<'a> {
    let x = Box::new(|| { z; });
    let y = Box::new(|| { z; });
    Foo {
      x,
      y,
    }
  }
}

但是,此实现会给出错误:

closure may outlive the current function, but it borrows 'z', which is owned by the current function

我可以使用move,但我想通过引用来做。我怎样才能满足编译器的要求?

我目前的想法是将函数和闭包设置为相同的生命周期,但我无法找到相关的文档。

rust closures lifetime
1个回答
4
投票

我可以使用move但我想通过引用来做。我怎样才能满足编译器的要求?

在这种情况下,您通过引用来完成它。 z已经是一个参考,所以你会move一个参考。通过省略move,你创建了一个新的&'b &'a str类型的引用(&'b只存在于你的函数内)。

© www.soinside.com 2019 - 2024. All rights reserved.