Casting fn() to usize inside an async block

Hi everyone!

I'm stuck here for a day on a compilation error that I would like to better understand. Here is the code:

use tokio;

pub async fn spawn(f: fn() -> u64) {
    tokio::spawn(async {
        helper(f as usize).await;
    });
}

async fn helper(f: usize) {}

I'm trying to pass a function pointer to the helper function as an usize. I'm doing something similar in other parts of the codebase, but this one I just can't get to compile when it's wrapped into an async {}.

I get the following error:

error[E0597]: `f` does not live long enough
 --> src/stdlib/process_.rs:6:16
  |
5 |        tokio::spawn(async {
  |   __________________-_____-
  |  |__________________|
  | ||
6 | ||         helper(f as usize).await;
  | ||                ^ borrowed value does not live long enough
7 | ||     });
  | ||     -
  | ||_____|
  | |______value captured here by generator
  |        argument requires that `f` is borrowed for `'static`
8 |    }
  |    - `f` dropped here while still borrowed

Even if I change my function definition to pub async fn spawn(f: &'static fn() -> u64) I get another error: cycle detected when processing spawn.

This makes even less sense to me. Is there any way to get this code to compile?

Add move (to async).

1 Like