无法执行tokio :: boxed Future,因为绑定了Send的特征不满足 [英] Unable to tokio::run a boxed Future because the trait bound Send is not satisfied
问题描述
我有一个函数,根据参数的不同,应该可以选择将来运行还是不执行任何操作.我尝试在要返回的两个期货周围放置一个Box
,一个立即解析为Ok(())
的tokio::prelude::future::Done<Item=(), Error=()>
,以及一个我正在使用and_then
和map_err
将两个Item
和Error
至()
.当我尝试使用tokio::run
运行期货时,这似乎对我不起作用.
I have a function that should optionally run a future or do nothing, depending on parameters. I tried putting a Box
around the two futures that will be returned, a tokio::prelude::future::Done<Item=(), Error=()>
that immediately resolves to Ok(())
, and a tokio::timer::Delay
that I'm using and_then
and map_err
to turn both the Item
and Error
to ()
. This doesn't seem to work for me when I try to run the futures with tokio::run
.
extern crate tokio;
use std::time::{Duration, Instant};
use tokio::prelude::*;
use tokio::timer;
fn main() {
tokio::run(foo(12));
}
fn foo(x: i32) -> Box<Future<Item = (), Error = ()>> {
if x == 0 {
Box::new(
timer::Delay::new(Instant::now() + Duration::from_secs(5))
.and_then(|_| Ok(()))
.map_err(|_| ()),
)
} else {
Box::new(future::result(Ok(())))
}
}
这无法编译并显示以下错误消息:
This fails to compile with the following error message:
error[E0277]: the trait bound `tokio::prelude::Future<Error=(), Item=()>: std::marker::Send` is not satisfied
--> src/main.rs:8:5
|
8 | tokio::run(foo(12));
| ^^^^^^^^^^ `tokio::prelude::Future<Error=(), Item=()>` cannot be sent between threads safely
|
= help: the trait `std::marker::Send` is not implemented for `tokio::prelude::Future<Error=(), Item=()>`
= note: required because of the requirements on the impl of `std::marker::Send` for `std::ptr::Unique<tokio::prelude::Future<Error=(), Item=()>>`
= note: required because it appears within the type `std::boxed::Box<tokio::prelude::Future<Error=(), Item=()>>`
= note: required by `tokio::run`
看来Box<Future...>
没有实现Send
,这对我来说没有意义.由于我要返回的Future
类型都实现了Send
,所以在我看来Box
应该应该这样做,因为impl Send for Box<T> where T: Send
是stdlib中的自动实现.我在这里想念什么?
It appears that Box<Future...>
does not implement Send
, which doesn't make sense to me. Since the Future
types that I'm returning both implement Send
, it seems to me that the Box
should, since impl Send for Box<T> where T: Send
is an auto implement in the stdlib. What am I missing here?
推荐答案
我意识到我需要在Foo
的返回类型中指定将来是Send
.编译:
I realized that I need to specify in the return type to Foo
that the future is Send
. This compiles:
extern crate tokio;
use std::time::{Duration, Instant};
use tokio::prelude::*;
use tokio::timer;
fn main() {
tokio::run(foo(12));
}
fn foo(x: i32) -> Box<Future<Item = (), Error = ()> + Send> { // note the + Send at the end of this line
if x == 0 {
Box::new(
timer::Delay::new(Instant::now() + Duration::from_secs(5))
.and_then(|_| Ok(()))
.map_err(|_| ()),
)
} else {
Box::new(future::result(Ok(())))
}
}
这篇关于无法执行tokio :: boxed Future,因为绑定了Send的特征不满足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!