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

Rust递归查找Cargo.toml异常:仅返回根目录文件的CLI程序问题

解决递归查找Cargo.toml文件的问题

你的代码无法捕获子目录中的Cargo.toml文件,核心原因是递归调用find_cargo_files时,没有将子目录返回的结果合并到当前的文件列表中,递归结果被直接丢弃了。同时代码里的panic!也不符合Rust的错误处理规范,容易导致程序崩溃。

修改方案

  • 接收递归调用返回的文件列表,用extend方法追加到当前列表
  • 替换panic!为返回Err,让错误可以被上层处理
  • 用if let替代unwrap,避免潜在的运行时panic

修改后的完整代码

use std::fs;
use std::path::{Path, PathBuf};
use std::io;

pub fn find_cargo_files(dir: &Path) -> Result<Vec<String>, io::Error> {
    let mut cargo_files: Vec<String> = Vec::new();

    if !dir.exists() {
        return Err(io::Error::new(io::ErrorKind::NotFound, "Directory not found"));
    }

    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();

        if path.is_dir() {
            // 合并子目录的查找结果
            let sub_files = find_cargo_files(&path)?;
            cargo_files.extend(sub_files);
        } else if path.is_file() {
            // 安全判断文件名是否为Cargo.toml
            if let Some(file_name) = path.file_name().and_then(|name| name.to_str()) {
                if file_name == "Cargo.toml" {
                    if let Some(path_str) = path.to_str() {
                        cargo_files.push(path_str.to_string());
                    }
                }
            }
        }
    }

    Ok(cargo_files)
}

验证结果

修改后重新运行,输出会包含所有子目录中的Cargo.toml文件:

Files : ["../test/Cargo.toml", "../test/files/Cargo.toml"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:20:26