I am using the following package https://docs.rs/z3/latest/z3/ to interact with an SMT solver. However the package has some lifetime uses which I am not able to create a wrapper for.
My goal is to be able to store a Solver in a struct and have a Wrapper::new() method without needing to specify the context of the solver.
The solver takes a reference to a context, so the context must live as long as the wrapper. If only the solver would take ownership of the context, the issue would be solved, but unfortunately i cannot change the library.
I tried the following: (both with and without comments) but both don't work because of referencing a variable in local scope.
I am pretty new to lifetimes so I don't really know how to solve this issue. Do you have any ideas/directions to be able to store such a solver?
Thanks in advance!
What you're trying to do (effectively) is called a self-referential struct, ie, a struct which has one field which stores a reference to another field. This is not allowed in Rust.
To be more specific:
You are getting the "reference-to-temporary" error since the variable ctx is freed once new returns, but the Wrapper you are returning still refers to it. Hence that would be a dangling reference and is hence not allowed.
If you try to store ctx by value instead in Wrapper, you'd end up with the self-referential problem.
One slightly bad way to solve your problem is to use Box::leak. Effectively, you are allocating memory for the Context and forgetting about it, allowing it to leak. This solves the reference error, but if you allocate a lot of Wrappers, then you would end up leaking all the memory.
Thanks for your quick reply and a possible solution! In my use case I would like to be able to create a large amount of solvers and be able to cleanup ones that are no longer in use. Is there any other way this can be solved? Or is this a the consequence of a design decision in the z3 crate?
The consequence is that you cannot store the Context and the Solver in the same struct. You can store them in separate structs, or separately at top level.