Hello all, I'm new to Rust and coming from typescript/haskell. I'm attempting to implement something along the lines of:
use std::future::Future;
async fn add_one(i: i32) -> Option<i32> {
Some(i + 1)
}
async fn to_none(i: i32) -> Option<i32> {
None
}
#[tokio::main]
async fn main() {
let mut futures: Vec<fn(i32) -> dyn Future<Output = Option<i32>>> = vec![];
futures.push(add_one); // Error
futures.push(to_none); // Error
// mismatched types
// expected fn pointer `fn(_) -> (dyn std::future::Future<Output = std::option::Option<i32>> + 'static)`
// found fn item `fn(_) -> impl std::future::Future {add_one}`rustc(E0308)
for fut in &futures {
match fut(1).await {
// Error
// the size for values of type `dyn std::future::Future<Output = std::option::Option<i32>>` cannot be known at compilation time
// the trait `std::marker::Sized` is not implemented for `dyn std::future::Future<Output = std::option::Option<i32>>`
// to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
// all local variables must have a statically known size
// unsized locals are gated as an unstable featurerustc(E0277)
Some(num) => println!("Future returned {:?}.", num),
None => println!("Didn't get a number."),
}
}
}
As far as I can tell the first error has to do with the types defined for the futures vector. I would like to leave the add_one
and to_none
functions alone and not muck with their types, so changing the type for the futures vector seems appropriate, but I'm not sure how to do that either!
The second error is getting into correct usage of Sized. Unfortunately, the std docs for Sized are a little inscrutable to me. Maybe I should add + ?Sized
somewhere, but I don't understand where that would be or why, which is not how I prefer to learn things. Any advice would be appreciated! Thanks.
Anyway, hope you are all enjoying your social distance and keeping safe, fed, and healthy!