Let's say we have this code:
fn inc(src: u32) -> u32 {
src + 1
}
fn inc2(src: u32) -> u32 {
src + 2
}
type Incrementer = fn(u32) -> u32;
fn increment_printer(inc: Incrementer) {
println!("{}", inc(1));
}
fn main() {
increment_printer(inc);
increment_printer(inc2);
}
Two functions with the same signature and a 3rd one that accepts pointers for them. Running this code results in:
2
3
being printed.
But something similar won't compile:
use core::future::Future;
async fn inc(src: u32) -> u32 {
src + 1
}
async fn inc2(src: u32) -> u32 {
src + 2
}
type Incrementer = fn(u32) -> dyn Future<Output = u32>;
async fn increment_printer(inc: Incrementer) {
println!("{}", inc(1).await);
}
fn main() {
async {
increment_printer(inc).await;
increment_printer(inc2).await;
}
}
18 | increment_printer(inc).await;
| ^^^ expected trait object `dyn Future`, found opaque type
|
= note: expected fn pointer `fn(_) -> (dyn Future<Output = u32> + 'static)`
found fn item `fn(_) -> impl Future {inc}`
I know that each async function has its own type, as mentioned in the error. Is it possible to force the compiler to forget about the concrete type and treat them as similar types?
Maybe it's possible to force an async function to return a Box<Future<Output=u32>>?
I don't want to give up async functions for convenience. Also I don't want to require calling Box::pin() before passing the async function pointer to the function.
It would be interesting to know if there are more options.