返回传递给函数的不可变引用后面的可变引用

Returning a mutable reference that is behind an immutable reference, passed to the function

如何返回不可变引用后面的可变引用,作为参数传递给函数,如何处理?

struct Foo { i: i32 }

struct Bar<'b> {
    f: &'b mut Foo
}

impl<'a: 'b, 'b> Bar<'b> {
    fn func(&'a self) -> &'b mut Foo {
         self.f
    }
}

fn main() {
    let mut foo = Foo { i: 1 };

    let bar = Bar { f: &mut foo };
    bar.func(); 
}

给出以下错误:

error[E0389]: cannot borrow data mutably in a `&` reference
 --> src/main.rs:9:14
  |
8 |         fn func(&'a self) -> &'b mut Foo {
  |                 -------- use `&'a mut self` here to make mutable
9 |              self.f
  |              ^^^^^^ assignment into an immutable reference

我(有点)理解编译器在这里试图阻止什么。但是我对错误消息感到困惑 assignment into an immutable referenceself(或 self.f 内部)究竟分配了什么?

我写了下面的代码来模拟这个问题,得到了同样的错误信息,和上面的不同,我能理解。这是代码:

fn main() {
    let mut foo = Foo { i: 1 };

    let bar = Bar { f: &mut foo };
    let pbar = &bar;

    pbar.f.i = 2; // assignment into an immutable reference
}

在第一个例子中,它是否试图将可变引用 f 移出 self(因为 &mut 不是 Copy 类型),处理它作为不可变引用 self 内的突变,因此出现错误消息 assignment into an immutable reference?

您不能从不可变引用创建可变引用。这意味着您需要将 &self 更改为 &mut self:

impl<'a: 'b, 'b> Bar<'b> {
    fn func(&'a mut self) -> &'b mut Foo {
         self.f
    }
}

现在你的变量需要是可变的,这样你就可以为方法获取一个可变引用:

let mut bar = Bar { f: &mut foo };
bar.func(); 

What exactly is being assigned into self (or inside of self.x?) ?

错误信息可能有点不对劲。您的代码中没有赋值,但您返回了一个 mutable 引用。可变引用允许您在这里做的唯一额外的事情是分配 self.fself.f.i.

当然可以改进此错误消息,但它确实包含使 &'a self 可变以解决问题的提示。

现在,你原来的问题:

How is returning a mutable reference that is behind an immutable reference, passed as an argument to the function, handled?

Rust 为内部可变性提供了多种容器类型,例如 CellRefCell。这些类型负责确保编译器的正确性,并使其成为运行时检查。将 RefCell 应用于您的代码的一种方法可能是这样的:

use std::cell::RefCell;
use std::ops::DerefMut;

struct Foo { i: i32 }

struct Bar<'b> {
    // store the data in a RefCell for interior mutability
    f: &'b RefCell<Foo>
}

impl<'a: 'b, 'b> Bar<'b> {
    // Return a RefMut smart pointer instead of mutable ref, but hide the implementation,
    // just exposing it as something that can be mutably dereferenced as a Foo
    fn func(&'a self) -> impl DerefMut<Target = Foo> + 'b {
         self.f.borrow_mut()
    }
}

fn main() {
    let foo = RefCell::new(Foo { i: 1 });
    let bar = Bar { f: &foo };

    let mut f = bar.func(); 
    f.i = 3;
}