Skip to content

Commit b75327c

Browse files
Add an example of a higher ranked closure returning boxed future
1 parent f0c1eb4 commit b75327c

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

posts/inside-rust/2024-08-09-async-closures-call-for-testing.md

+13-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,19 @@ where
3434
F: FnOnce() -> Pin<Box<dyn Future<Output = String>>>;
3535
```
3636

37-
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`.
37+
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:
38+
39+
```rust
40+
fn async_callback<F, Fut>(callback: F)
41+
where
42+
F: FnOnce(&str) -> Pin<Box<dyn Future<Output = ()> + '_>>;
43+
44+
async fn do_something(name: &str) {}
45+
46+
async_callback(|name| Box::pin(async {
47+
do_something(name).await;
48+
}));
49+
```
3850

3951
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).
4052

0 commit comments

Comments
 (0)