我有一个带有方法
fn maybe_getv(&mut self) -> Option<&mut i32>
的结构。现在我想实现另一个名为“getv_with_retry”的函数,它在循环中不断重试并返回成功。
struct S {
v: i32,
}
impl S {
pub fn maybe_getv(&mut self) -> Option<&mut i32> {
unimplemented!(); // return Some(&mut self.v) in some cases
}
}
fn getv_with_retry(s: &mut S) -> Option<&mut i32> {
loop {
let result = s.maybe_getv();
if result.is_some() {
return result;
}
}
}
(链接到 Rust 游乐场:https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f6ca3e7d0a6c29a0e9d9cdcf902c7ad3)
编译器会报如下错误:
error[E0499]: cannot borrow `*s` as mutable more than once at a time
--> src/lib.rs:13:22
|
11 | fn getv_with_retry(s: &mut S) -> Option<&mut i32> {
| - let's call the lifetime of this reference `'1`
12 | loop {
13 | let result = s.maybe_getv();
| ^^^^^^^^^^^^^^ `*s` was mutably borrowed here in the previous iteration of the loop
14 | if result.is_some() {
15 | return result;
| ------ returning this value requires that `*s` is borrowed for `'1`
我应该如何正确实施
getv_with_retry
?