grrs 的第一個實作

經過上章節的指令稿引數後,我們已經取得了輸入資料,現在可以開始撰寫真正的工具。我們的 main 函式目前只包含這行

    let args = Cli::parse();

(我們刪除了之前為了示範程式正常運作而暫時加入的 println 陳述式。)

就從開啟我們取得的檔案開始吧。

    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);
        }
    }

結束

你的程式碼現在應該看起來像這樣

use clap::Parser;

/// Search for a pattern in a file and display the lines that contain it.
#[derive(Parser)]
struct Cli {
    /// The pattern to look for
    pattern: String,
    /// The path to the file to read
    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 應該能正常運作!