I'm using the structs Foo
and Bar
from a library and I'm getting a compilation error in the client code. I simplified the code to this:
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();
}
(playground)
Output:
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
The error in the console output is very clear, but I cannot fix the problem.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…