0
trying to use &self to call an async method of a struct within another async method. The compiler complains like so:
11 | async fn mult(&mut self) {
| ---------
| |
| `self` is a reference that is only valid in the associated function body
| let's call the lifetime of this reference `'1`
12 | self.a *= 2;
13 | tokio::spawn(self.disp());
| ^^^^^^^^^^^
| |
| `self` escapes the associated function body here
| argument requires that `'1` must outlive `'static`
While I understand that the compiler cannot guarantee that &self would outlive the execution of display, how do I even tackle this ? Calling the method as an associated function comes to mind, but that is most likely practical only in toy code snippets like this.
Code :
use tokio;
struct A {
a: i32,
}
impl A {
async fn disp(&self) {
println!("{}", self.a);
}
async fn mult(&mut self) {
self.a *= 2;
tokio::spawn(self.disp());
}
}
#[tokio::main]
async fn main() {
let c = A{a: 2};
c.mult();
}