如何为Option <closure>指定生命周期?

Chr*_*oph 8 syntax lifetime rust

我试图在一个应该持有的结构上放置一个字段Option<closure>.

然而,Rust正在向我大吼大叫,我必须指明它的生命周期(并不是说我真的会这么说).我正尽力做到这一点,但Rust对我提出的建议并不满意.看看我对我得到的编译错误的内联注释.

struct Floor{
    handler: Option<|| ->&str> //this gives: missing lifetime specifier 
    //handler: Option<||: 'a> // this gives: use of undeclared lifetime name `'a`
}

impl Floor {
    // I guess I need to specify life time here as well 
    // but I can't figure out for the life of me what's the correct syntax
    fn get(&mut self, handler: || -> &str){
        self.handler = Some(handler);
    }
}
Run Code Online (Sandbox Code Playgroud)

Bur*_*hi5 15

这有点棘手.

作为一般经验法则,无论何时在数据结构中存储借用的引用(即&类型),都需要命名其生命周期.在这种情况下,您使用a处于正确的轨道上'a,但'a必须在当前范围中引入.它与引入类型变量的方式相同.所以要定义你的Floor结构:

struct Floor<'a> {
    handler: Option<|| -> &'a str>
}
Run Code Online (Sandbox Code Playgroud)

但这里还有另一个问题.闭包本身也是一个具有生命周期的引用,也必须命名.所以这里有两种不同的生命周期!试试这个:

struct Floor<'cl, 'a> {
    handler: Option<||:'cl -> &'a str>
}
Run Code Online (Sandbox Code Playgroud)

对于您而言impl Floor,您需要将这些生命周期引入范围:

impl<'cl, 'a> Floor<'cl, 'a> {
    fn get(&mut self, handler: ||:'cl -> &'a str){
        self.handler = Some(handler);
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以在技术上将它减少到一个生命周期并使用||:'a -> &'a str,但这意味着&str返回的总是与闭包本身具有相同的生命周期,我认为这是一个不好的假设.

  • 哇哇,这完全让我头晕目眩.人们应该习惯这种疯狂吗?:-S (6认同)
  • @Christoph:如果您认为这很疯狂,请尝试使用您的`Floor`结构... (6认同)
  • @Christoph,希望当[unboxed closures](https://github.com/rust-lang/rfcs/pull/77/)降落时,关闭的情况会变得更好.例如,您将能够在结构中存储堆箱封闭,这不需要指定生命周期. (2认同)