I've been trying to push my understanding of lifetime, but I'm hitting this problem with my solution.
Pretty much the general design is that I have some large data in my base state.
I'm trying to generate streaming iterator to list all valid transformation of that state.
It would then return the base state with the transformation applied.
But I would like to return a guard to that state so that when the loop finish using it, the guard to revert the base state back to it's original valid, which then you can use the stream to build the next state.
Here is my minimum design looks like
struct DataGuard<'data> {
data: &'data mut usize,
}
impl<'data> Drop for DataGuard<'data> {
fn drop(&mut self) {
*self.data -= 10000;
}
}
struct DataStream<'data> {
data: &'data mut usize,
}
fn steam_entries<'data, 'stream: 'data>(stream: &'stream mut DataStream<'data>) -> DataGuard<'stream> {
*stream.data += 10000;
DataGuard { data: stream.data }
}
fn main() {
let mut data = 0;
let mut stream = DataStream { data: &mut data };
loop {
let guard = steam_entries(&mut stream);
// ... other statements
let _ = guard;
}
}
this returns with the compiler error
error[E0499]: cannot borrow `stream` as mutable more than once at a time
--> src/main.rs:23:35
|
23 | let guard = steam_entries(&mut stream);
| ^^^^^^^^^^^ mutable borrow starts here in previous iteration of loop
error: aborting due to previous error
My thought process would be that the DataGuard
indicated to live as long as DataStream
, so that when DataGuard
is drop at the end of the loop, there won't be anything holding onto DataStream
, and thus it would be safe to borrow DataStream
mutably again.
Help in understanding this is appreciated