【问题标题】:Can’t compile this code due to lifetime issue由于生命周期问题,无法编译此代码
【发布时间】:2021-05-09 19:22:47
【问题描述】:

编译这段代码:

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(&amp;'a mut i32)改成fn(&amp;mut i32),就编译成功了,这是为什么呢?

【问题讨论】:

    标签: rust lifetime


    【解决方案1】:

    问题源于函数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 的生命周期所推断的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多