I can't use self in closure! The code is here.
use std::thread;
struct MyManager;
impl MyManager {
pub fn run(&self) {
// 1. receive message in handler
let handler = |x: i32| {
// 2. then execute time-consuming computing in another thread, or cause blocking
// !!! FIXME:
// but the code below compile failed, please help me here.
thread::spawn(move || {
self.compute(x);
});
"ok".to_string()
};
self.init(Box::new(handler));
}
pub fn init(&self, handler: Box<dyn FnMut(i32) -> String>) {
println!("initiallized ...");
}
pub fn compute(&self, x: i32) {
println!("computing {}", x);
}
}
#[test]
pub fn basic() {
let manager = MyManager{};
manager.run();
}
Then according to the compiler prompt,I modify code to the following.
use std::thread;
struct MyManager;
impl MyManager {
pub fn run(&'static self) {
// 1. receive message in handler
let handler = |x: i32| {
// 2. then execute time-consuming computing in another thread, or cause blocking
// !!! FIXME:
// but the code below compile failed,
thread::spawn(move || {
self.compute(x);
});
"ok".to_string()
};
self.init(Box::new(handler));
}
pub fn init(&self, handler: Box<dyn FnMut(i32) -> String>) {
println!("initiallized ...");
}
pub fn compute(&self, x: i32) {
println!("computing {}", x);
}
}
#[test]
pub fn basic() {
let manager = MyManager{};
let manager = Box::leak(Box::new(manager));
}
But compile failed again and prompt the following error.
error[E0597]: `self` does not live long enough
--> src\learn\mymanager.rs:15:17
|
9 | let handler = |x: i32| {
| -------- value captured here
...
15 | self.compute(x);
| ^^^^ borrowed value does not live long enough
...
21 | self.init(Box::new(handler));
| ----------------- cast requires that `self` is borrowed for `'static`
22 |
23 | }
| - `self` dropped here while still borrowed
I don't know what to do and need some help please.