[英]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);
This code does not compile.此代码无法编译。
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
I get the above error instead.我得到了上面的错误。
Yes, immut_ref
borrows foo
immutably, however it is moved when we call foo.upgrade_ref
.是的,
immut_ref
不可变地借用了foo
,但是当我们调用foo.upgrade_ref
时它被移动了。 Therefore, there are no longer any references to foo
and I should be able to get a mutable reference to foo
.因此,不再有任何对
foo
的引用,我应该能够获得对foo
的可变引用。
Why does this not compile?为什么这不能编译?
upgrade_ref
takes &mut self
and ImmutRef<Self>
. upgrade_ref
采用&mut self
和ImmutRef<Self>
。 You're trying to pass it &mut foo
and &foo
at the same time.您正试图同时传递它
&mut foo
和&foo
。 But an immutable reference and mutable reference can't exist at the same time.但是不可变引用和可变引用不能同时存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.