03-第一次实现

实现第一版 grep 风格工具

译文 · 基于 Command Line Applications in Rust

第一次实现 grrs

原文链接: https://rust-cli.github.io/book/tutorial/impl-draft.html

在上一章讲完命令行参数之后, 我们已经有了输入数据, 可以开始编写真正的工具了。 目前 main 函数里只有这一行:

1
    let args = Cli::parse();

可以把临时放在那里、用来演示程序能正常工作的 println 删掉了。

先打开我们拿到的那个文件。

1
    let content = std::fs::read_to_string(&args.path).expect("could not read file");

接下来,遍历各行, 并打印每一行包含我们模式的内容:

1
2
3
4
5
    for line in content.lines() {
        if line.contains(&args.pattern) {
            println!("{}", line);
        }
    }

收尾

你的代码现在应如下所示:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
use clap::Parser;

/// 在文件中搜索模式并显示包含它的行。
#[derive(Parser)]
struct Cli {
    /// 要查找的模式
    pattern: String,
    /// 要读取的文件路径
    path: std::path::PathBuf,
}

fn main() {
    let args = Cli::parse();
    let content = std::fs::read_to_string(&args.path).expect("could not read file");

    for line in content.lines() {
        if line.contains(&args.pattern) {
            println!("{}", line);
        }
    }
}

试一试:cargo run -- main src/main.rs 现在应该能工作了!

最后修改 August 11, 2026: 更新 (70a5af133)