[英]Rust: allow upgrade of immutable reference to mutable reference, if no other references exist
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
。 但是不可變引用和可變引用不能同時存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.