Sorry about this, I feel stupid especially since I see I'm not the only one with this issue, and I still can't figure out a solution based on the answers I've seen here ![]()
So I have a struct:
pub struct DBWriter {
conn: Connection,
buffer: HashMap<String, (Info, u32)>,
}
It's a database connection and a data buffer of data so I can write in the database in a single transaction. This means that I have to access both, the connection and the buffer, so I have a function like this one:
fn save_game_buffer(&mut self) -> Result<()> {
let tx = self.conn_mut().transaction()?;
let mut buffer = &self.game_buffer;
let values = buffer.values();
for value in values {
// ... then use the transaction to add the data
}
tx.commit();
buffer.clear();
}
And as the more experienced rustacians here will notice, I'm getting the error:
cannot borrow `self.buffer` as immutable because it is also borrowed as mutable
immutable borrow occurs here
error[E0502]: cannot borrow `self.game_buffer` as immutable because it is also borrowed as mutable
--> src/data/writer/sqlite.rs:226:26
|
225 | let tx = self.conn_mut().transaction()?;
| ---- mutable borrow occurs here
226 | let mut buffer = &self.game_buffer;
| ^^^^^^^^^^^^^^^^^ immutable borrow occurs here
...
243 | tx.commit()?;
| -- mutable borrow later used here
So, I've tried every combination possible, and I still can't figure out how to solve the problem. Thing is, I kind of understand that for memory safety the compiler wants me to prevent having two mutable references to self, but what I actually want to change are two variables independent from each other.
How can I iterate the values that belong to the struct, while using the database connection that is also owned by the struct?
Edit: Sorry, my brain currently hurts now trying to figure it out, although on paper this should look like a trivial problem and this is what frustrates me the most, I still feel I haven't switched my mindset on how to approach apparently simple problems in Rust.