Hello guys,
I'm trying to implement a function, the function has an argument which is a closure.
Within the function, I create some local variable. and I pass the local variable to the closure. The variable will not be needed anymore once the closure returns.
I expected this to work, but I ended up receiving a lifetime error. Basically the local variable have a life time <'_> where as the closure's argument needs to have 'static. I don't understand this. Why does it have to be 'static. I followed some online instructions in an attempt to change that, but it didn't work.
here is my code:
pub fn transaction<'a, F>(&'a self, f: F) -> Result<(), &str>
where F: FnOnce(&'a HashMap<String, std::rc::Rc<std::cell::RefCell<dyn CollectionTrait>>>) -> Result<(), &'static str>
{
let mut conn = self.internal.borrow_mut();
let tx = std::rc::Rc::new( std::cell::RefCell::new( TransactionInternal{ connection: conn.connection.transaction().unwrap() }));
let mut collections: HashMap<String, std::rc::Rc<std::cell::RefCell<dyn CollectionTrait>>> = HashMap::new();
let tx_weak = std::rc::Rc::downgrade(&tx);
for (key, value) in &self.collections {
collections.insert(key.to_string(), std::rc::Rc::new(RefCell::new(Collection::<false, true, false, false> {
name: key.to_string(),
db: tx_weak.clone(),
table_name: key.to_string(),
})));
}
let transaction = Transaction {
tx: Rc::downgrade(&tx)
};
f(&collections).unwrap();
// tx.commit().unwrap();
Err("Not implemented")
}
the error I received was this
error[E0759]: `self` has lifetime `'a` but it needs to satisfy a `'static` lifetime requirement
--> src/database.rs:392:38
|
389 | pub fn transaction<'a, F>(&'a self, f: F) -> Result<(), &str>
| -------- this data with lifetime `'a`...
...
392 | let mut conn = self.internal.borrow_mut();
| ------------- ^^^^^^^^^^
| |
| ...is captured here...
...
411 | f(&collections).unwrap();
| ------------ ...and is required to live as long as `'static` here
it says the variable has a lifetime 'a, which I understand. but when I pass it into the closure, it has to be 'static. I don't understand this part and is a way to change this? Thanks!