Hello, I am novice in Rust and I am struggling with following code:
pub struct TgSchedulerLive {
client: Client,
period: Interval,
scheduler_handle: Option<JoinHandle<()>>,
text: String,
is_running: bool,
}
impl TgSchedulerLive {
...
async fn run(&self) -> () {
let mut dialog_iter = self.client.iter_dialogs();
while let Ok(Some(dialog)) = dialog_iter.next().await {
println!("{}", dialog.chat.name().unwrap_or_default());
}
}
}
impl TgScheduler for TgSchedulerLive {
...
fn start(&mut self) -> () {
let mut scheduler = AsyncScheduler::new();
scheduler
.every(self.period)
.run(|| self.run());
self.stop();
...
The signature of method run:
/// Specify a task to run, and schedule its next run
///
/// The function passed into this method should return a value implementing `Future<Output = ()>`.
pub fn run<F, T>(&mut self, f: F) -> &mut Self
where
F: 'static + FnMut() -> T + Send,
T: 'static + Future<Output = ()> + Send,
{
self.job = Some(Box::new(JobWrapper::new(f)));
self.schedule.start_schedule();
self
}
I get the following error:
error[E0521]: borrowed data escapes outside of method
--> src/scheduling.rs:51:9
|
48 | fn start(&mut self) -> () {
| ---------
| |
| `self` is a reference that is only valid in the method body
| let's call the lifetime of this reference `'1`
...
51 | / scheduler
52 | | .every(self.period)
53 | | .run(|| self.run());
| | ^
| | |
| |_______________________________`self` escapes the method body here
| argument requires that `'1` must outlive `'static`
I also tried this:
fn start(&mut self) -> () {
async fn run(client: &Client, text: &String) {
let mut dialog_iter = client.iter_dialogs();
while let Ok(Some(dialog)) = dialog_iter.next().await {
println!("{}", dialog.chat.name().unwrap_or_default());
}
}
let mut scheduler = AsyncScheduler::new();
let client = self.client.clone();
let text = self.text.clone();
scheduler.every(self.period).run(move || run(&client, &text));
But i get the error:
error: captured variable cannot escape `FnMut` closure body
--> src/scheduling.rs:53:50
|
50 | let client = self.client.clone();
| ------ variable defined here
...
53 | scheduler.every(self.period).run(move || run(&client, &text));
| - ^^^^^------^^^^^^^^
| | | |
| | | variable captured here
| | returns an `async` block that contains a reference to a captured variable, which then escapes the closure body
| inferred to be a `FnMut` closure
|
= note: `FnMut` closures only have access to their captured variables while they are executing...
= note: ...therefore, they cannot allow references to captured variables to escape
Could you please explain how to get this code work?