Code
type callback = fn(cx) -> impl Future<Output = ()> + 'static + Send + Sync;
Error
impl Trait` only allowed in function and inherent method return types, not in `Fn` trait return`
Is there any alternative?
Thank you
Code
type callback = fn(cx) -> impl Future<Output = ()> + 'static + Send + Sync;
Error
impl Trait` only allowed in function and inherent method return types, not in `Fn` trait return`
Is there any alternative?
Thank you
Alternatives in this case depend on what properties the solution needs to have and which it doesn't. Show us how you intend to use the type, preferably with enough code to try compiling a solution.
Here is a short snippet
impl Future
can't be used like this since each function returns a different Future
type. What might be better here is to use a BoxFuture
. Would something like this work? (Rust Playground)
use futures::{future::BoxFuture, Future};
use std::marker::Send;
type Callback = Box<dyn Fn() -> BoxFuture<'static, ()>>;
struct Store {
fns: Vec<Callback>,
}
impl Store {
fn add<T, F>(&mut self, cb: F)
where
F: Fn() -> T + 'static,
T: Future<Output = ()> + Send + 'static,
{
self.fns.push(Box::new(move || Box::pin(cb())));
}
}
async fn f1() -> () {
println!("Hello");
}
async fn f2() -> () {
println!("Goodbye");
}
fn main() {
let mut s = Store { fns: Vec::new() };
s.add(f1);
s.add(f2);
}
Is it necessary to call the function when pushing?
Can not we just push the function without calling it?
e.g.
self.fns.push(Box::new(move || Box::pin(cb)));
Here, we don't actually call the function when we push it. Notice the move ||
: it means that the function call is in a new closure, so that the function is called only when the closure is called. Effectively, we're creating a wrapper function that calls the original function and boxes its Future
.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.