You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust使用ignore crate遍历目录,如何排除目录自身条目?

解决ignore crate Walk遍历目录时输出起始目录的问题

你可以通过两种方式过滤掉起始目录条目,具体取决于你的需求:

方式一:只列出所有文件(跳过所有目录)

如果你的目标是仅展示目录中的文件(不包含任何目录项),可以在处理条目时检查路径是否为文件:

use ignore::Walk;

for file in Walk::new("/tmp/foo_directory") {
    match file {
        Ok(entry) => {
            // 仅处理文件类型的条目
            if entry.path().is_file() {
                println!("{}", entry.path().display());
            }
        }
        Err(err) => println!("Error: {}", err),
    }
}

方式二:保留子目录但排除起始根目录

如果需要展示子目录但只想去掉起始的根目录条目,可以对比条目的路径与起始路径:

use ignore::Walk;
use std::path::Path;

let root = Path::new("/tmp/foo_directory");
for file in Walk::new(root) {
    match file {
        Ok(entry) => {
            // 跳过起始根目录本身
            if entry.path() != root {
                println!("{}", entry.path().display());
            }
        }
        Err(err) => println!("Error: {}", err),
    }
}

原因说明

ignore::Walk的默认行为会将你传入的起始目录作为第一个遍历结果返回,因此需要手动添加过滤逻辑来排除它。

内容的提问来源于stack exchange,提问作者bzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 23:47:07