Hi everyone . I would like to implement the following: I have some condition which is decided at runtime and, based on the outcome of this decision, I would like to call one of two asynchronous functions with a similar signature. Something like the following situation:
use std::future::Future;
async fn calling_conditionally(situation: Situation) -> String {
/// determine which function to call (first compiler error)
let func = match situation {
Situation::A => func_a,
Situation::B => func_b,
};
call_correct_function(func).await
}
enum Situation {
A,
B,
}
async fn func_a() -> String {
"doing 'a' stuff".to_owned()
}
async fn func_b() -> String {
"doing 'b' stuff".to_owned()
}
/// defining a function which takes the function to call as input argument (second compiler error)
async fn call_correct_function<F>(func: F) -> String
where
F: Fn() -> dyn Future<Output = String>,
{
func().await
}
With this I get a first compiler error saying that it "expected a future, but found a different future".
... and a second error saying that the "the trait Sized
is not implemented for dyn Future<Output = String>
".
I understand that I could get the above situation to work by directly calling the appropriate function in the match block of the situation, but would like to understand (a) why the compiler sees the two functions as different types and whether there is a different way of conditionally assigning one of two functions to a variable and (b) how I could write a function such that it takes an asynchronous function as a parameter and calls it.
Thanks a lot!