I've discussed the problems of caching sqlite statements here multiple times. Time to do it again
I previously solved this with mutable statics. It's ugly, but it works. Unhappy with the ugliness, I decided to try to cache the statements in the global structure I pass around immutably. So the type of each statement field is RefCell<Option<Statement<'l>>>.
I am also using the gtk crate in this application. The closures that serve as callbacks are defined as 'static by gtk. Sometimes I need these callbacks to have access to the global struct I pass around, so when that is required, I pass the struct wrapped in an Rc. At the point in the code where the callback closure gets connected to the signal handler, I clone the global struct and define the closure as a 'move' closure, and reference the clone inside the closure, so it is the clone that gets captured.
Here's the issue: if I define a function like so:
pub fn new_account(globals:Rc<Globals>) {
and then inside this function, I connect a callback to a signal handler, like so:
/* Handle the "changed" signal of the pattern entry.
The commodity combobox will be populated by the callback per the pattern */
let commodity_editing_changed = commodity_editing.clone();
let connect_changed_globals = globals.clone();
commodity_editing.pattern_item.connect_changed(move |_| {
pattern_text_changed(&commodity_editing_changed, connect_changed_globals.clone());
});
I get this compilation error:
158 | pub fn new_account(globals:Rc<Globals>) {
| ----------- help: add explicit lifetime `'static` to the type of `globals`: `std::rc::Rc<constants::Globals<'static>>`
...
248 | commodity_editing.pattern_item.connect_changed(move |_| {
| ^^^^^^^^^^^^^^^ lifetime `'static` required
error: aborting due to previous error
For more information about this error, try `rustc --explain E0621`.
error: Could not compile `newcash`.
What confuses me is that I am capturing a clone of the Rc'ed struct whose lifetime the compiler is complaining about and the closure has ownership of that clone, so I do not understand why there is a lifetime issue. And furthermore, why is does the fix involve lying about the lifetime of struct that is cloned, not the clone itself. And I say "lying" because the global struct does not have a static lifetime. It's created early in the main program and lives until the program exits, but it is not defined as static. It is a local variable in the main function.
Following the compiler's advice does fix the problem. But I'm uncomfortable because I don't understand what's going on here, so the end doesn't justify the means for me. Can someone please explain this?
And yes, I looked at the explanation of E0621 and got nothing from it.