Как использовать синтаксис async / await с Tokio? - PullRequest
0 голосов
/ 24 февраля 2019

Я пытаюсь использовать async / await с процессами в Rust.Я использую tokio и tokio-process:

#![feature(await_macro, async_await, futures_api)]

extern crate tokio;
extern crate tokio_process;

use std::process::Command;
use tokio_process::CommandExt;

fn main() {
    tokio::run_async(main_async());
}

async fn main_async() {
    let out = Command::new("echo")
        .arg("hello")
        .arg("world")
        .output_async();
    let s = await!(out);
}

Вот ошибка, которую я получаю:

error[E0277]: the trait bound `tokio_process::OutputAsync: std::future::Future` is not satisfied
  --> src/main.rs:21:13
   |
21 |     let s = await!(out);
   |             ^^^^^^^^^^^ the trait `std::future::Future` is not implemented for `tokio_process::OutputAsync`
   |
   = note: required by `std::future::poll_with_tls_waker`
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

error[E0277]: the trait bound `tokio_process::OutputAsync: std::future::Future` is not satisfied
  --> src/main.rs:21:13
   |
21 |     let s = await!(out);
   |             ^^^^^^^^^^^ the trait `std::future::Future` is not implemented for `tokio_process::OutputAsync`
   |
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

Как мне правильно это сделать?

1 Ответ

0 голосов
/ 24 февраля 2019

Tokio и связанные с ним ящики реализованы с использованием стабильного фьючерса 0.1 ящика.Черта Future из этого ящика концептуально похожа на версию черты Future из стандартной библиотеки, но существенно отличается в деталях.Синтаксис async / await построен вокруг версии признака в стандартной библиотеке.

Выполнение поиска в Интернете по запросу «tokio async await» приводит к метко названному ящику tokio-async-await .Ниже описывается, как разрешить Tokio участвовать в нестабильных фьючерсах:

[dependencies]
tokio = { version = "0.1.15", features = ["async-await-preview"] }
tokio-process = "0.2.3"

В вашем коде вы должны выполнить преобразование между Future, реализованным на основе характеристики из ящика фьючерсов 0.1 и из стандартной библиотеки.Простой способ сделать это - использовать Tokio-версию макроса await:

#![feature(await_macro, async_await, futures_api)]

use std::process::Command;
use tokio_process::CommandExt;

fn main() {
    tokio::run_async(main_async());
}

async fn main_async() {
    let out = Command::new("echo")
        .arg("hello")
        .arg("world")
        .output_async();
    let s = tokio::await!(out);
    println!("{:?}", s);
}
$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.10s
     Running `target/debug/oo`
Ok(Output { status: ExitStatus(ExitStatus(0)), stdout: "hello world\n", stderr: "" })

Протестировано с:

  • Rust 1.34.0-nightly (e1c6d0057 2019-02-22)
  • Ржавчина 1.34.0-ночью (aadbc459b 2019-02-23)

См. также:

...