【发布时间】:2021-06-13 18:36:24
【问题描述】:
在这段代码中:
struct Obj<'a> {
inside: &'a mut i32
}
fn take_and_return<'o>(obj: Obj<'o>) -> Obj<'o> {
obj
}
fn run_me_1() {
let mut v = 42;
let s: Obj<'_> = Obj {
inside: &mut v
};
take_and_return(s);
}
我想在run_me_1 中为s 引入命名生命周期。
我使用了 Rust Analyzer 的建议:
fn run_me_2<'a>() {
let mut v = 42;
let s: Obj<'a> = Obj {
inside: &mut v
};
take_and_return(s);
}
然后我得到以下错误:
error[E0597]: `v` does not live long enough
--> src/lib.rs:20:11
|
17 | fn run_me_2<'a>() {
| -- lifetime `'a` defined here
18 | let mut v = 42;
19 | let s: Obj<'a> = Obj {
| ------- type annotation requires that `v` is borrowed for `'a`
20 | inside: &mut v
| ^^^^^^ borrowed value does not live long enough
...
23 | }
| - `v` dropped here while still borrowed
我的理解是take_and_return拥有obj的所有权,所以obj必须永远存在,所以'o必须永远存在。这就解释了为什么run_me_2 无法编译。
我的问题是:
- 为什么
run_me_1编译? - 推断者在
run_me_1中的'_中添加了什么? - 如何修复
run_me_2以便编译?
【问题讨论】:
-
我认为这是一个 XY 问题。当您没有任何输入参数受其限制时,为什么需要该通用生命周期参数
'a?如果您不使用它,那么只需将其删除 - 问题就解决了。