struct Foo {
val: i32
}
impl Foo {
pub fn maybe_get(&mut self) -> Option<&mut i32> {
Some(&mut self.val)
}
pub fn definitely_get(&mut self) -> &mut i32 {
{ // Add closure to ensure things have a chance to get dropped
if let Some(val) = self.maybe_get() {
// Explicit return to avoid potential scope sharing with an else block or a match arms.
return val;
}
}
// One would think any mutable references would not longer be at play at this point
&mut self.val
}
}
我有一些代码,它比上面提供的更加复杂,而且我已经努力解决了相当长一段时间。借用检查程序不满意definitely_get
的实现,并出现以下错误:
error[E0499]: cannot borrow `self.val` as mutable more than once at a time
--> src/main.rs:19:9
|
10 | pub fn definitely_get(&mut self) -> &mut i32 {
| - let's call the lifetime of this reference `'1`
11 | {
12 | if let Some(val) = self.maybe_get() {
| ---------------- first mutable borrow occurs here
13 | return val;
| --- returning this value requires that `*self` is borrowed for `'1`
...
19 | &mut self.val
| ^^^^^^^^^^^^^ second mutable borrow occurs here
似乎没有办法在可变引用中实现回退逻辑,这似乎是不合理的。我无法想象没有任何方法可以解决这个问题。
cargo +nightly rustc -- -Zpolonius
编译)。 - Chayim Friedmanstd::ptr::addr_of_mut
。你需要使用一个不安全的块来实现这个操作,但在这种情况下是正确的。我有一些相当复杂的数据结构,也遇到了类似的问题,不幸的是。 - GManNickG