I am a novice and do not know how to handle the following code:
async fn run<F>(
&self,
user: User
tasks: Option<Vec<F>>,
) where
F: std::future::Future<Output = Result<UserResult, Error>>,
F: Send + 'static,
{
xxx
}
// Ok
async fn main(){
let user = User { };
let tasks = Some(xxx);
run(user,tasks ).await;
}
// Error cannot infer type for type parameter `F` declared on the associated function `run`
async fn main(){
let user = User { };
run(user, None).await;
}
How should I handle this situation?
What do you mean by "a generic type parameter that can be NULL"? The function either has them, or doesn't. Are you saying you want F
to be inferred from the call site?
You have to specify F
to some concrete type like run::<std::future::Pending<_>>(user, None);
1 Like
While the previous answer is right, you need to specify the generic type parameter, it seems to me to point to a different problem. Why would you want to run no tasks? Does it really make sense for run()
to accept an Option of tasks? Wouldn't it make more sense to just do nothing when tasks is None?
let user = User { };
let tasks = Some(xxx);
if let Some(tasks) = tasks {
run(user, tasks).await
}
I would go even further and not recommend using Option at all. An empty Vec is a much better representation for this use case. 99% of the time, Option<Vec<T>>
is not what you want.
3 Likes
This is only a schematic code, please ignore rationality
Sometimes I bring some tasks, sometimes I don't
Thank you, the code can now be compiled through.