In the following example, the rust compiler is complaining that I am borrowing bar as mutable and immutable at the same time. Why is that so ? Why are the borrows accuring at the same time and not one after the other ?
What I would like is to be able to use .buffers and .buffers_bind in a method inside of Bar.
struct BufferBinding<'a> {
bind: &'a Buffer
}
struct Buffer {
name: String,
}
struct Bar<'a> {
buffers: Vec<Buffer>,
buffers_bind: Vec<BufferBinding<'a>>
}
impl<'a> Bar<'a> {
pub fn new<'b>() -> Bar<'b> {
Bar {
buffers: vec![],
buffers_bind: vec![]
}
}
pub fn add(&'a mut self, name: String) {
self.buffers.push(Buffer {name});
self.buffers_bind.push(BufferBinding {
bind: &self.buffers.last().unwrap()
})
}
pub fn do_smh(&self) -> Vec<i32> {
// this is meant to do something with self.buffers_bind and self.buffers
vec![1, 2, 3]
}
}
fn main() {
let mut bar = Bar::new();
bar.add(String::from("buf1"));
bar.add(String::from("buf2")); //cannot borrow `bar` as mutable more than once at a time
let result = bar.do_smh();
println!("{:?}", result);
}
Looking more closely, the issue is that your struct is self-referential. It's impossible to have references in one field point into another field of the same struct. References can only go between two completely separate variables.