调用tokio :: spawn时,如何解决“特征绑定`[closure]:tokio :: prelude :: Future`不满意”的问题?

时间:2019-10-22 11:08:59

标签: rust rust-tokio

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`

Playground

1 个答案:

答案 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);
}