How can one method of a structure run another method of the same structure as a task?
Forgive me for possible stupidity, I'm new to Rust.
The compiler complains that self
cannot survive the body of the function in which it is called. But isn't this accessing the context of a structure that is, by definition, alive, since its methods can be called?
use std::time::{Duration};
use async_std::{task, task::JoinHandle, prelude::*};
async fn sleep(delay: f64) -> () {
task::sleep(Duration::from_secs_f64(delay)).await;
}
struct TestTask {
item: usize,
count: usize
}
impl TestTask {
fn new() -> TestTask {
return Self { item: 0, count: 0 }
}
async fn task(&mut self, delay: f64) -> () {
sleep(delay).await;
println!("AFTER SLEEP {}sec, value = {}", delay, self.item);
self.item += 1;
}
fn create_task(&mut self, delay: f64) -> () {
task::spawn(self.task(delay));
self.count += 1;
}
}
async fn test_task() -> () {
let mut obj = TestTask::new();
let delay: f64 = 5.0;
obj.create_task(delay);
sleep(delay + 1.0).await;
println!("DELAY SLEEP {:?}sec", delay + 1.0);
}
#[async_std::main]
async fn main() {
test_task().await;
}