How do I solve “the trait bound `[closure]: tokio::prelude::Future` is not satisfied” when calling tokio::spawn?

感情迁移 提交于 2019-12-02 11:25:16
Ö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);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!