如何使用tokio 0.1和异步函数递归删除目录?

时间:2019-11-12 17:58:32

标签: asynchronous rust

我想编写一个程序,该程序在Rust 1.39中使用异步功能递归删除目录。

第一步,我尝试了以下代码,但未编译:

use std::env;
use failure::Error;
use futures::Future;
use std::path::PathBuf;
use tokio::prelude::*;

fn walk(path: PathBuf) -> Box<dyn Future<Item = (), Error = Error> + Send> {
    let task = tokio::fs::read_dir(path)
        .flatten_stream()
        .for_each(move |entry| {
            let filepath = entry.path();
            if filepath.is_dir() {
                future::Either::A(walk(filepath))
            } else {
                println!("File: {:?}", filepath);
                future::Either::B(future::ok(()))
            }
        })
        .map_err(Error::from)
        .and_then(|_| {
            println!("All tasks done");
        });
    Box::new(task)
}

fn main() -> Result<(), std::io::Error> {
    let args: Vec<String> = env::args().collect();
    let dir = &args[1];
    let t = walk(PathBuf::from(&dir)).map_err(drop);
    tokio::run(t);
    Ok(())
}

运行cargo build时,得到以下输出:

error[E0220]: associated type `Item` not found for `core::future::future::Future`
  --> src\main.rs:10:42
   |
10 | fn walk(path: PathBuf) -> Box<dyn Future<Item = (), Error = Error> + Send> {
   |                                          ^^^^^^^^^ associated type `Item` not found

error[E0220]: associated type `Error` not found for `core::future::future::Future`
  --> src\main.rs:10:53
   |
10 | fn walk(path: PathBuf) -> Box<dyn Future<Item = (), Error = Error> + Send> {
   |                                                     ^^^^^^^^^^^^^ associated type `Error` not found

error[E0191]: the value of the associated type `Output` (from the trait `core::future::future::Future`) must be specified
  --> src\main.rs:10:31
   |
10 | fn walk(path: PathBuf) -> Box<dyn Future<Item = (), Error = Error> + Send> {
   |                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ associated type `Output` must be specified

Cargo.toml:

[dependencies]
async-std = "1.0.1"
failure = "0.1.6"
futures = "0.3.1"
tokio = "0.1.22"

有帮助吗?

1 个答案:

答案 0 :(得分:1)

您使用的是Future 0.3,而Tokio 0.1尚不支持。而是导入Tokio并使用其prelude模块,该模块重新导出它支持的futures版本:

use std::{env, path::PathBuf};
use tokio::prelude::*; // 0.1.22

type Error = Box<dyn std::error::Error + Send + Sync>;

fn walk(path: PathBuf) -> Box<dyn Future<Item = (), Error = Error> + Send> {
    let task = tokio::fs::read_dir(path)
        .flatten_stream()
        .map_err(Error::from)
        .for_each(|entry| {
            let filepath = entry.path();
            if filepath.is_dir() {
                future::Either::A(walk(filepath))
            } else {
                println!("File: {:?}", filepath);
                future::Either::B(future::ok(()))
            }
        })
        .inspect(|_| {
            println!("All tasks done");
        });
    Box::new(task)
}

fn main() -> Result<(), std::io::Error> {
    let args: Vec<String> = env::args().collect();
    let dir = &args[1];
    let t = walk(PathBuf::from(&dir)).map_err(drop);
    tokio::run(t);
    Ok(())
}

您还需要在flatten_stream之后转换错误,并且不能将and_thenprintln!一起使用,因为它不会返回将来。使用inspect进行副作用调试。

通常,您不需要仅使用一个参数(使用Iterator::nth)就收集所有参数,也不需要使用PathBuf作为参数。目前尚不清楚为什么要从Result返回一个main,因为它永远不可能是Err

另请参阅: