Tokio 0.2 and lifetimes

Hello.
I have a problem with wrapping tokio runtime in my impl trait.
How to fix it?

My code:

use async_trait::async_trait;

#[async_trait]
trait MyTrait
{
    async fn run(&mut self);
    async fn test(&mut self);
}

struct MyStruct{}

#[async_trait]
impl MyTrait for MyStruct
{
    async fn test(&mut self)
    {
       ///... any code
    }

    async fn run(&mut self)
    {
        let mut rt = Runtime::new().unwrap();

        rt.block_on(async move {
            ///... any code
            tokio::spawn(async move { self.test(); });
          });
     }
}

Error:

error: cannot infer an appropriate lifetime
   --> src/main.rs:833:23
    |
833 |     async fn run(&mut self)
    |                       ^^^^ ...but this borrow...
...
840 |             tokio::spawn(async move {
    |             ------------ this return type evaluates to the `'static` lifetime...
    |
note: ...can't outlive the lifetime `'_` as defined on the function body at 725:1

You should not create a runtime inside an async fn, since to call an async fn, you must already be on a runtime.

Ok. How to fix? How wrap tokio::runtime?

Since you want run to move self into a spawned task, it must take self by value.

trait MyTrait
{
    async fn run(self);
    async fn test(&mut self);
}

struct MyStruct{}

#[async_trait]
impl MyTrait for MyStruct
{
    async fn test(&mut self) {
       /// ... any code
    }

    async fn run(self) {
        tokio::spawn(async move {
            self.test();
        });
    }
}

This means that run owns self, so it is allowed to move it to another task.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.