Add async functions to hashmap

This is enough for the code sample it seems.

type CallbackFuture<'a> = dyn Future<Output = Response<BoxBody<Bytes, Error>>> + Send + 'a;
type CallbackFn = fn(SocketAddr, &Uri) -> Pin<Box<CallbackFuture<'_>>>;
    let bp_serve_file: CallbackFn = |addr, uri| Box::pin(serve_file(addr, uri));
    let bp_not_found: CallbackFn = |addr, uri| Box::pin(not_found(addr, uri));

    let mut funcs = HashMap::new();
    funcs.insert("docs", bp_serve_file);

    let result = funcs.get(&selector).copied().unwrap_or(bp_not_found);

It may not have been clear from my above comment, but

  • async fn return opaque types (impl Future ...)
  • Every opaque type is unique
  • fn pointers with different output types are themselves different types
  • Therefore two async fn can never coerce to the same fn pointer type

The workaround is type erase the future (Pin<Box<dyn ...>>) so that you can have function pointers with the same type.

3 Likes