这是对我的问题的一个可重复的简化:
struct Val<'a>(&'a str);
impl Val<'_> {
fn get(&self) -> Option<&str> {
Some(self.0)
}
}
// Not used here, but this borrow needs to be mutable
fn test<'a>(param: &'a mut Val<'a>) -> Option<&'a str> {
param.get()
}
fn main() {
let s = String::from("hello");
let mut v = Val(&s);
while let Some(x) = test(&mut v) {
println!("{x}");
}
}
我得到了:
|
17 | while let Some(x) = test(&mut v) {
| ^^^^^^
| |
| `v` was mutably borrowed here in the previous iteration of the loop
| first borrow used here, in later iteration of loop
For more information about this error, try `rustc --explain E0499`.
首先,我try 更改borrow 的生存期,以指示它没有原始数据的生存期长,如下所示:
fn test<'a, 'b>(param: &'b mut Val<'a>) -> Option<&'a str> {
param.get()
}
But then 我得到了:
|
9 | fn test<'a, 'b>(param: &'b mut Val<'a>) -> Option<&'a str> {
| -- -- lifetime `'b` defined here
| |
| lifetime `'a` defined here
10 | param.get()
| ^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b`
|
= help: consider adding the following bound: `'b: 'a`
添加建议的界限会让我回到前面的错误.
我选中了this related question,这表明这是borrow 判断器的限制,因此我try 将代码更改为:
fn main() {
let s = String::from("hello");
let mut v = Val(&s);
loop {
let x = test(&mut v);
if let Some(y) = x {
println!("{y}");
}
}
}
但我得到了相同的第一个错误.在我的用例中,test
的行为或多或少类似于next
from迭代器,因此我不能在同一迭代中调用它两次.
有没有办法:
- 是否返回生存期为
'a
而不是fn test
中的'b
的数据? - 或者,对于单一的
'a
生命周期,使borrow 在迭代结束时被删除?
Edit:当翻译回我真正的问题时,我注意到这个例子并不能完全代表它,我仍然在使它工作方面有问题.我对示例here进行了一些更改,并在生命周期中进行了一些额外的更改以使其正常工作.现在它运行得很好.总而言之,test
函数必须对get
返回的值进行一些映射,在这个过程中,它返回的是生存期'b
而不是'a
.