由于生命周期问题无法编译此代码

Can’t compile this code due to lifetime issue

编译这段代码:

fn foo<'a>(f: fn(&'a mut i32), x: &'a mut i32) {
    f(x);
    f(x);
}

我收到以下错误:

error[E0499]: cannot borrow `*x` as mutable more than once at a time
 --> src\main.rs:3:7
  |
1 | fn foo<'a>(f: fn(&'a mut i32), x: &'a mut i32) {
  |        -- lifetime `'a` defined here
2 |     f(x);
  |     ----
  |     | |
  |     | first mutable borrow occurs here
  |     argument requires that `*x` is borrowed for `'a`
3 |     f(x);
  |       ^ second mutable borrow occurs here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0499`.
error: could not compile `scratch`

To learn more, run the command again with --verbose.

但是如果我将 f 的类型从 fn(&'a mut i32) 更改为 fn(&mut i32),它编译成功,这是为什么?

这个问题是因为函数 f 有一个显式的参数 'a。这意味着它 必须 'a 借用它的参数 x,这是它的整个生命周期,导致双重借用错误。您正在寻找 higher-ranked trait bounds,它允许函数本身具有另一个可以相应缩短的通用生命周期:

fn foo<'a>(f: for<'b> fn(&'b mut i32), x: &'a mut i32) {
    f(x);
    f(x);
}

在不指定任何显式生命周期的情况下,这就是 Rust 的生命周期推断的结果。