Skip to content

Commit

Permalink
Add an example of a higher ranked closure returning boxed future
Browse files Browse the repository at this point in the history
  • Loading branch information
compiler-errors committed Aug 14, 2024
1 parent f0c1eb4 commit b75327c
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion posts/inside-rust/2024-08-09-async-closures-call-for-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,19 @@ where
F: FnOnce() -> Pin<Box<dyn Future<Output = String>>>;
```

This led to an additional limitation, that it's impossible to express higher-ranked async fn bounds without boxing, since a higher-ranked trait bound on `F` cannot lead to a higher-ranked type for `Fut`.
This led to an additional limitation, that it's impossible to express higher-ranked async fn bounds using this without boxing, leading to unnecessary allocations:

```rust
fn async_callback<F, Fut>(callback: F)
where
F: FnOnce(&str) -> Pin<Box<dyn Future<Output = ()> + '_>>;

async fn do_something(name: &str) {}

async_callback(|name| Box::pin(async {
do_something(name).await;
}));
```

These limitations were detailed in [Niko's blog post on async closures and lending](https://smallcultfollowing.com/babysteps/blog/2023/05/09/giving-lending-and-async-closures/#async-closures-are-a-lending-pattern), and later in compiler-errors's blog post on [why async closures are the way they are](https://hackmd.io/@compiler-errors/async-closures).

Expand Down

0 comments on commit b75327c

Please sign in to comment.