gpt4 book ai didi

rust - 如何解决 "the trait bound ` [closure]: tokio::prelude::Future` is not satisfied"when calling tokio::spawn?

转载 作者:行者123 更新时间:2023-11-29 08:25:58 27 4
gpt4 key购买 nike

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 )

最佳答案

请检查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

Creates a new future which will eventually be the same as the one created by the closure provided.

简单地说,一个lazy future 拥有一个闭包来执行。这发生在执行程序第一次执行 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);
}

关于rust - 如何解决 "the trait bound ` [closure]: tokio::prelude::Future` is not satisfied"when calling tokio::spawn?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58502916/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com