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`
答案 0 :(得分:2)
请检查definition of tokio::spawn
:
pub fn spawn<F>(f: F) -> Spawn
where
F: Future<Item = (), Error = ()> + 'static + Send
它期望将Future
的实现作为其参数。您传递给tokio::spawn
的闭包不是Future
的实现。 Futures-rs拥有lazy
创建一个新的未来,最终将与所提供的闭包创建的未来相同。
简而言之,lazy
的将来拥有一个要执行的闭包。这是在执行程序第一次执行poll
时发生的(在这种情况下,您使用的是Tokio执行程序)。
如果用lazy
包装闭包,则代码将按预期工作。
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);
}