I'm trying to write a very simple draw batcher. I've created a minimal version of the issue:
struct DrawBatch<'a> {
triangles : &'a mut i32,
}
struct Batch<'a> {
draw_batch : Vec<DrawBatch<'a>>,
default_count : i32
}
impl<'a> Batch<'a> {
fn circle<'e: 'a>(&'e mut self) {
// a circle is made up of multiple triangles (fan)
self.triangle();
self.triangle();
}
fn triangle<'m : 'a>(&'m mut self) {
// draws a triangle
let batch = self.get_last_batch();
// modify the batch, add triangles, etc
*batch.triangles += 1;
println!("triangle count: {}", batch.triangles);
}
fn get_last_batch<'r : 'a>(&'r mut self) -> &mut DrawBatch {
if self.draw_batch.is_empty() {
// there must always be at least one draw batch
self.draw_batch.push(DrawBatch { triangles: &mut self.default_count });
}
return self.draw_batch.last_mut().unwrap();
}
}
fn main() {
let de = 0;
let mut b = Batch{ draw_batch: Vec::new(), default_count : de };
b.circle();
}
You can play it here: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a89d11f89680962554e486fd05f129ab
The error is:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:13:9
|
9 | impl<'a> Batch<'a> {
| -- lifetime `'a` defined here
...
12 | self.triangle();
| ---------------
| |
| first mutable borrow occurs here
| argument requires that `*self` is borrowed for `'a`
13 | self.triangle();
| ^^^^^^^^^^^^^^^ second mutable borrow occurs here
I truly don't understand the problem. The first borrow is clearly finished after I borrow again. I've tried multiple ways of setting the lifetimes but I could not find the right configuration.
Why is triangles a reference??
triangles : &'a mut i32,
In reality this is something else (A material
struct specifically) I just wanted to keep things light and don't introduce more structs.
The question this was close for has absolutely nothing to do with my question. Different errors. This question is not about storing a object + object reference in the same struct.