如何在Tokio中使用async / await语法?

Hri*_*lev 4 rust async-await rust-tokio

我正在尝试对Rust中的进程使用异步/等待。我正在使用tokiotokio-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);
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

#![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);
}
Run Code Online (Sandbox Code Playgroud)

我该如何正确处理?

She*_*ter 7

Tokio 0.1和相关的板条箱使用稳定的期货0.1板条箱实现。Future此板条箱的特征在概念上与Future标准库中特征的版本相似,但细节上有很大不同。async/ await语法围绕标准库中的特征版本构建。

尚未发布的Tokio 0.2和相关的板条箱是使用标准库实现的Future,正在进行重新设计以提供更好的支持async/ await语法。

东京0.2

[dependencies]
tokio = "0.2.0-alpha.2"
tokio-process = "0.3.0-alpha.2"
Run Code Online (Sandbox Code Playgroud)
use tokio_process::Command;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let out = Command::new("echo")
        .arg("hello")
        .arg("world")
        .output()
        .await?;

    let s = String::from_utf8_lossy(&out.stdout);

    println!("{}", s);
    Ok(())
}
Run Code Online (Sandbox Code Playgroud)
[dependencies]
tokio = "0.2.0-alpha.2"
tokio-process = "0.3.0-alpha.2"
Run Code Online (Sandbox Code Playgroud)

经过测试:

  • Rustc 1.39.0-nightly(6ef275e6c 2019-09-24)

东京0.1

您必须在Future针对期货0.1板条箱的特性与标准库之间的实现之间进行转换。

use futures_03::{compat::Future01CompatExt, FutureExt, TryFutureExt};
use std::process::Command;
use tokio_process::CommandExt;

fn main() {
    tokio::run({
        // Convert from 0.3 to 0.1
        main_async().map(Ok).boxed().compat()
    });
}

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

    // Convert from 0.1 to 0.3
    let s = out.compat().await;

    println!("{:?}", s);
}
Run Code Online (Sandbox Code Playgroud)
use tokio_process::Command;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let out = Command::new("echo")
        .arg("hello")
        .arg("world")
        .output()
        .await?;

    let s = String::from_utf8_lossy(&out.stdout);

    println!("{}", s);
    Ok(())
}
Run Code Online (Sandbox Code Playgroud)
[dependencies]
tokio = "0.1.22"
tokio-process = "0.2.4"
futures-03 = { package = "futures", version = "0.3.1", features = ["compat"] }
Run Code Online (Sandbox Code Playgroud)

经过Rust 1.39.0测试

也可以看看: