First of all I want to apologise for this noob question with an unspecific title, I'm quite new to Rust.
Anyway, here is some (working) code:
struct A {
data: i32
}
struct B<'s> {
a: &'s A
}
impl<'s> B<'s> {
fn new(reference: &'s A) -> B<'s> {
B {
a: reference
}
}
}
fn main() {
let a1 = A{data: 0};
let b1 = B::new(&a1);
let b2 = B::new(&a1);
}
There is a struct A with some data and a struct B that contains an immutable reference to A. In the main method several B-objects are created with references to a single A-object.
Now I only want to change one thing: In the B::new() method I want to modify the data of 'reference' before using it as the immutable member of B. I tried it like this:
struct A {
data: i32
}
struct B<'s> {
a: &'s A
}
impl<'s> B<'s> {
fn new(reference: &'s mut A) -> B<'s> {
// Modify data
reference.data += 1;
B {
a: reference
}
}
}
fn main() {
let mut a1 = A{data: 0};
let b1 = B::new(&mut a1);
let b2 = B::new(&mut a1);
}
But the compiler won't let me, error: cannot borrow a1
as mutable more than once at a time. Why isn't the mutable borrow over once new() has finished? What would be the proper way to achieve what I'm trying?