rust - 无法 tokio::run 盒装 Future,因为不满足特征绑定(bind) Send

标签 rust rust-tokio

<分区>

我有一个函数,可以根据参数选择运行 future 或什么也不做。我试着放一个 Box围绕将返回的两个 future ,一个tokio::prelude::future::Done<Item=(), Error=()>立即解析为 Ok(()) , 和一个 tokio::timer::Delay我正在使用 and_thenmap_errItemError() .当我尝试使用 tokio::run 运行 future 时,这似乎对我不起作用.

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 的返回类型中指定 future 是 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(())))
    }
}

关于rust - 无法 tokio::run 盒装 Future,因为不满足特征绑定(bind) Send,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51485410/

相关文章:

rust - 如何实现一个允许为字段赋值的过程宏?

rust - 如何创建自可变引用的 Rc<RefCell<>> ?

rust - 当多个 future 使用相同的基础套接字时,为什么不能将它们唤醒?

rust - 如何在warp中将传入流写入文件?

rust - 如何阅读基于 Tokio 的 Hyper 请求的整个主体?

rust - 发送到数组中的每个 futures::sync::mpsc::Sender

rust - 什么是解决 future 需要多长时间的干净方法?

rust - 如何使用 Serde 序列化具有顶级键的结构?

rust - 是否有理由在 Substrate 中对特定类型使用通用特征?

recursion - Rust 中任意递归期间变异状态的惯用所有权管理