Last active
January 30, 2023 11:48
-
-
Save Denys-Bushulyak/144bb32fbc843298e863e5a841e543de to your computer and use it in GitHub Desktop.
Example of the function add that accepts an asynchronous callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 pinnedBox
. Thankfully, theBoxFuture
shorthand exists for this. If you look at the code, you will see thatBoxFuture
is defined as pub typeBoxFuture<'a, T> = Pin<alloc::boxed::Box<dyn Future<Output = T> + Send + 'a>>
.