简体   繁体   English

获取对不可变变量的可变引用?

[英]Obtain a mutable reference to a immutable variable?

Here's the code, since a is declared as immutable, we can't obtain a mutable reference from a , right?这是代码,因为a被声明为不可变的,我们不能从a获得可变引用,对吗? But this one has compiled, why is that?但是这个编译出来了,这是为什么呢?

struct Foo;

fn main() {
    let a = &mut Foo;
    a.mut_ref();
}

impl Foo {
    fn mut_ref(&mut self) { }
}

code-link 代码链接

The type of the variable a is &mut Foo , ie a itself is a mutable reference to a Foo object. Mutating a would mean to make it point to a different Foo object. Since a itself is immutable, you can't change what a is pointing to, and your code does not disprove this in any way.变量a的类型是&mut Foo ,即a本身是对Foo object 的可变引用。改变a意味着使其指向不同的Foo object。由于a本身是不可变的,因此您无法更改a是什么指向,并且您的代码不会以任何方式反驳这一点。

Your code simply passes the &mut Foo as the self parameter to mut_ref() – note that the type of self is also &mut Foo .您的代码只是将&mut Foo作为self参数传递给mut_ref() – 请注意, self的类型也是&mut Foo No auto-dereferencing is happening – a already has exactly the type that is epxected for the self parameter.没有发生自动解引用——a 已经完全a self参数所期望的类型。 However, we are triggering an implicit reborrow here, so the call is equivalent to Foo::mut_ref(&mut *a) .然而,我们在这里触发了一个隐式的重借,所以这个调用等同于Foo::mut_ref(&mut *a) This implicit reborrow isn't what's making the code work, though – moving the mutable reference out of a would also be perfectly allowed.但是,这种隐式的重新借用并不是使代码工作的原因——将可变引用移出a也是完全允许的。

While a is immutable as a variable, it's still a mutable reference, so you can mutate the Foo object it's pointing to (assuming Foo had any state to mutate).虽然a作为变量是不可变的,但它仍然是可变引用,因此您可以改变它指向的Foo object(假设Foo有任何 state 可以改变)。 You can't obtain a mutable reference to a , which would need to have the type &mut &mut Foo .您无法获得对a的可变引用,它需要具有类型&mut &mut Foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM