簡體   English   中英

Rust:如果不存在其他引用,則允許將不可變引用升級為可變引用

[英]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 selfImmutRef<Self> 您正試圖同時傳遞它&mut foo&foo 但是不可變引用和可變引用不能同時存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM