How can I call an objects method which takes a mutable reference to self, without moving the object into the method scope?
The following code shows a very simple struct, which has two attributes 1) a vector of ints 2) a vector of optional references to those ints:
struct MyStruct<'a> {
vec: Vec<i32>,
ref_vec: Vec<&'a i32>
}
impl <'a> MyStruct <'a>{
fn new() -> MyStruct<'a>{
MyStruct{
vec: Vec::new(),
ref_vec: Vec::new(),
}
}
fn add_int(&'a mut self, value: i32, reference: bool){
self.vec.push(value);
let n = self.vec.len();
if reference == true {
self.ref_vec.push(&self.vec[n-1])
}
}
}
fn main() {
let mut v = MyStruct::new();
v.add_int(55, true);
println!("Added element is {}", v.ref_vec[0])
}
What I would like it to do is to add 55
to v.vec
and to add a reference to v.vec[0]
to v.ref_vec
.
It does do this, but in doing so v
is borrowed by add_int
(even though add_int
only takes a mutable reference to self
), and thus v.ref_vec[0]
is not able to perform the required borrow in the final line.
output:
--> src/main.rs:30:37
|
28 | v.add_int(55, true);
| ------------------- mutable borrow occurs here
29 |
30 | println!("Added element is {}", v.ref_vec[0])
| ^^^^^^^^^
| |
| immutable borrow occurs here
| mutable borrow later used here
How can I call the method add_int
without losing the ability to reference it later?