不能借用不可变的因为它也被借用为可变的

dmg*_*vil 5 rust

我正在使用结构FooBar库,我在客户端代码中收到编译错误.我将代码简化为:

use std::marker::PhantomData;

struct Foo {
    some_str: &'static str,
}

struct Bar<'a> {
    some_str: &'static str,
    marker: PhantomData<&'a Foo>,
}

impl Foo {
    fn read_data(&self) {
        // add code here
    }
    fn create_bar<'a>(&'a mut self) -> Bar<'a> {
        Bar {
            some_str: "test2",
            marker: PhantomData,
        }
    }
}

fn process(_arr: &mut [Bar]) {}

fn main() {
    let mut foo = Foo { some_str: "test" };
    let mut array: [Bar; 1] = [foo.create_bar()];
    process(&mut array);
    foo.read_data();
}
Run Code Online (Sandbox Code Playgroud)

(游乐场)

输出:

error[E0502]: cannot borrow `foo` as immutable because it is also borrowed as mutable
  --> src/main.rs:30:5
   |
28 |     let mut array: [Bar; 1] = [foo.create_bar()];
   |                                --- mutable borrow occurs here
29 |     process(&mut array);
30 |     foo.read_data();
   |     ^^^ immutable borrow occurs here
31 | }
   | - mutable borrow ends here
Run Code Online (Sandbox Code Playgroud)

控制台输出中的错误非常清楚,但我无法解决问题.

aSp*_*pex 5

您可以array通过将变量放置在带有花括号 ( { ... })的新作用域中来限制变量的生命周期:

fn main() {
    let mut foo = Foo { some_str: "test" };
    {
        let mut array: [Bar; 1] = [foo.create_bar()];
        process(&mut array);
    }
    foo.read_data();
}
Run Code Online (Sandbox Code Playgroud)