【发布时间】:2023-01-07 01:59:07
【问题描述】:
struct ImmutRef<'a, T>(&'a T);
struct MutRef<'a, T>(&'a mut T);
struct Foo;
impl Foo {
fn upgrade_ref(&mut self, _: ImmutRef<Self>) -> MutRef<Self> {
MutRef(self)
}
}
let mut foo = Foo;
let immut_ref = ImmutRef(&foo);
let mut_ref = foo.upgrade_ref(immut_ref);
此代码无法编译。
error[E0502]: cannot borrow `foo` as mutable because it is also borrowed as immutable
--> src/main.rs:63:16
|
62 | let immut_ref = ImmutRef(&foo);
| ---- immutable borrow occurs here
63 | let mut_ref = foo.upgrade_ref(immut_ref);
| ^^^^-----------^^^^^^^^^^^
| | |
| | immutable borrow later used by call
| mutable borrow occurs here
我得到了上面的错误。
是的,immut_ref不变地借用foo,但是当我们调用foo.upgrade_ref时它被移动了。因此,不再有任何对 foo 的引用,我应该能够获得对 foo 的可变引用。
为什么这不能编译?
【问题讨论】:
-
upgrade_ref需要&mut self和ImmutRef<Self>。您正在尝试同时传递&mut foo和&foo。但是不可变引用和可变引用不能同时存在。 -
@PitaJ 顺便说一句,如果你想发布它,那是一个答案
标签: rust borrow-checker