extern crate tokio; // 0.1.22
use tokio::io;
use tokio::net::TcpListener;
use tokio::prelude::*;
use bytes::Bytes; // 0.4.12
fn main() {
let addr = "0.0.0.0:1502".parse().unwrap();
let mut listener = TcpListener::bind(&addr).unwrap();
let done = listener
.incoming()
.map_err(|e| println!("failed to accept socket; error = {:?}", e))
.for_each(move |socket| {
let process = move || {};
tokio::spawn(process)
});
tokio::run(done);
Ok(());
tokio::run(done);
}
error[E0277]: the trait bound `[closure@src/main.rs:17:27: 17:37]: tokio::prelude::Future` is not satisfied
--> src/main.rs:19:13
|
19 | tokio::spawn(process)
| ^^^^^^^^^^^^ the trait `tokio::prelude::Future` is not implemented for `[closure@src/main.rs:17:27: 17:37]`
|
= note: required by `tokio::spawn`
Ömer Erden
Please check the definition of tokio::spawn:
pub fn spawn<F>(f: F) -> Spawn
where
F: Future<Item = (), Error = ()> + 'static + Send
It expects an implementation of Future as its argument. The closure you passed into tokio::spawn is not an implementation of Future. Instead of a closure, Futures-rs has lazy
Creates a new future which will eventually be the same as the one created by the closure provided.
Simply, a lazy future holds a closure to execute. This happens on the first execution of poll made by the executor (in this case you are using Tokio executor).
If you wrap your closure with lazy, your code will work as you expected.
extern crate tokio; // 0.1.22
use tokio::net::TcpListener;
use tokio::prelude::*;
fn main() {
let addr = "0.0.0.0:1502".parse().unwrap();
let listener = TcpListener::bind(&addr).unwrap();
let done = listener
.incoming()
.map_err(|e| println!("failed to accept socket; error = {:?}", e))
.for_each(move |_socket| {
let process = futures::future::lazy(move || {
println!("My closure executed at future");
Ok(())
});
tokio::spawn(process)
});
tokio::run(done);
}
来源:https://stackoverflow.com/questions/58502916/how-do-i-solve-the-trait-bound-closure-tokiopreludefuture-is-not-satis