【问题标题】:Rust: allow upgrade of immutable reference to mutable reference, if no other references existRust:如果不存在其他引用,则允许将不可变引用升级为可变引用
【发布时间】: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需要&amp;mut selfImmutRef&lt;Self&gt;。您正在尝试同时传递&amp;mut foo&amp;foo。但是不可变引用和可变引用不能同时存在。
  • @PitaJ 顺便说一句,如果你想发布它,那是一个答案

标签: rust borrow-checker


【解决方案1】:

upgrade_ref需要&amp;mut selfImmutRef&lt;Self&gt;。您正在尝试同时传递&amp;mut foo&amp;foo。但是不可变引用和可变引用不能同时存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多