The problem here is that you're trying to create a self-referential struct, and doing so (with actual references) doesn't really work out in Rust . For example here:
#[derive(Debug)]
struct Look<'a> {
n: i32,
r: Option<&'a i32>,
}
impl<'a> Look<'a> {
fn new(n: i32) -> Self {
Look { n, r: None }
}
fn init(&'a mut self) -> &'a Self {
self.r = Some(&self.n);
self
}
}
You can manage to create the self-referential struct...
// Works...
let mut look = Look::new(0);
// Works...
look.init();
...but then you can't actually use it!
// error[E0502]: cannot borrow `look` as immutable because it is also borrowed as mutable
println!("{look:?}");
Why not? Because in order to initialize the r
field, you needed a reference with a lifetime of length 'a
; to get such a borrow out of self
, you needed a &'a mut Self
. So in order to call look.init()
, you had to mutably -- or more accurately put, exclusively -- borrow look
for the entirety of its remaining validity. Once you create that exclusive borrow, it is impossible to use look
again, except through that borrow.
You can't print it. You can't move it, so you can't return it. You can't even run a destructor if you have one.
Why does it work this way? Well, consider what would happen if you could move look
after you created it: you would move the thing that r
is referencing, and r
would dangle. (Rust does not have move constructors.) Something has to prevent that from happening.
You may say, well in my case the referenced value is on the heap, but Rust the language has no distinction between references to the heap or to the stack.
Not only that, but Rust's aliasing rules dictate that nothing can have exclusive access to the n
field so long as there's a live reference that can observe it. So something has to prevent another &mut look
from being created, no matter where the referenced value is in memory.
And there are probably other, similar reasons as well.
ZipFile
has a Drop
desctructor, so this is probably why you can't even construct your Test
. If you don't need to gradually read the ZipFile
, you could just store its index in the ZipArchive
. If you do need to gradually read, what you probably want is Seek
support, but apparently the plan is to have that for raw (compressed) data, and not for ZipFile
. I didn't look into it, but maybe seeking requires uncompressing everything anyway.
This issue looks to mirror your use-case.