Skip to content

Instantly share code, notes, and snippets.

@Denys-Bushulyak
Last active January 30, 2023 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Denys-Bushulyak/144bb32fbc843298e863e5a841e543de to your computer and use it in GitHub Desktop.
Save Denys-Bushulyak/144bb32fbc843298e863e5a841e543de to your computer and use it in GitHub Desktop.
Example of the function add that accepts an asynchronous callback
use futures::future::BoxFuture;
#[tokio::main]
async fn main() {
let words = vec!["one", "two"];
let result = add(words, |word| {
Box::pin(async {
let mut kw = word;
kw.push("three");
kw
})
})
.await;
assert_eq!(result.len(), 3);
assert!(result.contains(&"one"));
assert!(result.contains(&"two"));
assert!(result.contains(&"three"));
dbg!(result);
}
pub async fn add<'input_words, F, Output>(words: Vec<&'input_words str>, callback: F) -> Vec<Output>
where
F: Fn(Vec<&'input_words str>) -> BoxFuture<'input_words, Vec<Output>>,
{
let mut result = vec![];
result.extend(callback(words).await);
result
}
@Denys-Bushulyak
Copy link
Author

Denys-Bushulyak commented Jan 30, 2023

A little explanation is needed. In the add function, you can't just return Future<'input words, Vec<Output> because its size is not pre-known. That's why it must be wrapped in a pinned Box. Thankfully, the BoxFuture shorthand exists for this. If you look at the code, you will see that BoxFuture is defined as pub type BoxFuture<'a, T> = Pin<alloc::boxed::Box<dyn Future<Output = T> + Send + 'a>>.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment