隐式类型闭包的生命周期推断错误

And*_*nin 5 closures type-inference lifetime rust

这是简单的复制(截至 2023 年 2 月 2 日的每晚 rustc):

fn main() {
    let closure = |_v| {};
    // this one works fine
    // let closure = |_v: &_| {};
    {
        let x = 1;
        closure(&x);
    }
    {
        let y = 1;
        closure(&y);
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是:

6  |         let x = 1;
   |             - binding `x` declared here
7  |         closure(&x);
   |                 ^^ borrowed value does not live long enough
8  |     }
   |     - `x` dropped here while still borrowed
...
11 |         closure(&y);
   |         ------- borrow later used here
Run Code Online (Sandbox Code Playgroud)

这是没有意义的,因为变量x没有被 捕获closure,而只是通过引用传递的参数。

为闭包参数提供显式引用_v: &_可以解决问题,但不应该自动推断吗?

这是借用检查器的一些错误/限制吗?或者我在这里遗漏了一些更基本的东西?

pig*_*nds 5

对我来说,这看起来可能是类型推断的错误。

我认为正在发生的事情是

fn main() {
    let closure = |_v| {};

    { 
        let x = 1; // Lifetime `a begins
        closure(&x); // closure is inferred to be fn(&'a i32)
        // Lifetime 'a end
    }
    {
        let y = 1; // Lifetime `b begins
        closure(&y); // attempt to call closure fn(&'a i32) with &'b i32
        // Lifetime 'b end
    }
}
Run Code Online (Sandbox Code Playgroud)

但将闭包定义为

let closure = |_v: &'_ i32| {};
Run Code Online (Sandbox Code Playgroud)

停止编译推断其生命周期并按其应有的方式使用hrtb

  • 我已经[提出了一个问题](https://github.com/rust-lang/rust/issues/107589)。 (2认同)