rust - 无法 tokio::run a boxed Future 因为 trait bound Send 不满足
问题描述
我有一个函数可以选择运行未来或什么都不做,具体取决于参数。我尝试将 a 放在Box
将返回的两个期货中,atokio::prelude::future::Done<Item=(), Error=()>
立即解析为Ok(())
,以及tokio::timer::Delay
我正在使用and_then
andmap_err
将两者都转换为Item
和。当我尝试使用.Error
()
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(())))
}
}
这无法编译并显示以下错误消息:
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
是标准库中的自动实现。我在这里想念什么?
解决方案
我意识到我需要在返回类型中指定Foo
未来是Send
. 这编译:
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(())))
}
}
推荐阅读
- image - 如何解决退出代码 139,用于在带有 WSL2 Ubuntu 的 docker 中运行图像 cloudera/quickstart?
- python - 有没有办法从谷歌云运行已经构建的 python API?
- python - 如何设置 Visual Studio Python 的工作目录以防止出现错误“No module named 'source'”
- azure - Azure 数据工厂通过服务主体将服务链接到 Synapse 无服务器池
- html - 显示:inline-block last-child 宽度 100% 与其同级不对齐
- c# - 我不明白示例中的某些内容
- python - Python:einsum 在 for 循环中
- ruby-on-rails - Heroku 部署 - Rails 6.1.3 - 捆绑安装失败 - Gemfile.lock 平台添加
- pandas - Pandas - 获取每个布尔字段的计数
- reactjs - Github Pages NPM 运行部署失败,错误代码为 ELIFECYCLE