小编xar*_*das的帖子

无法推断返回引用的闭包的适当生命周期

考虑以下代码:

fn foo<'a, T: 'a>(t: T) -> Box<Fn() -> &'a T + 'a> {
    Box::new(move || &t)
}
Run Code Online (Sandbox Code Playgroud)

我期待的是:

  • T型具有寿命'a.
  • 这个价值t只要有效T.
  • t 移动到关闭,所以关闭生活只要 t
  • 闭包返回一个引用t移动到闭包的引用.因此只要闭包存在,引用就是有效的.
  • 没有生命周期问题,代码编译.

实际发生了什么:

  • 代码无法编译:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
 --> src/lib.rs:2:22
  |
2 |     Box::new(move || &t)
  |                      ^^
  |
note: first, the lifetime cannot outlive the lifetime  as defined on the body at 2:14...
 --> src/lib.rs:2:14
  |
2 | …
Run Code Online (Sandbox Code Playgroud)

closures ownership rust borrowing

16
推荐指数
2
解决办法
967
查看次数

标签 统计

borrowing ×1

closures ×1

ownership ×1

rust ×1