眠気.jl

投稿=不定期

備忘録: RustのCLIチュートリアルのExcercise1.3

First implementation - Command Line Applications in Rust

Exercise for the reader: This is not the best implementation: It will read the whole file into memory – however large the file may be. Find a way to optimize it! (One idea might be to use a BufReader instead of read_to_string().)
とのことだったのでBuffReader使いました

書いたもの

#![allow(unused)]

use clap::Parser;
use std::io::BufReader;
use std::fs::File;
use std::io::BufRead;

/// 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
    #[clap(parse(from_os_str))]
    path: std::path::PathBuf,
}

fn main() {
    let args = Cli::parse();

    let content = File::open(&args.path).expect("could not read file");
    let mut reader = BufReader::new(content);
    let mut line = String::new();

    for line in reader.lines() {
        if line.as_ref().unwrap().contains(&args.pattern) {
            println!("{}", line.unwrap());
        }
    }
    println!("path = {:?}", args.path);
    println!("pattern = {:?}", args.pattern);
}

その他

もっといいやり方あるかも
Rustに詳しい私のアンチの方がいたらご教示ください。