Skip to content

Exercise solutions #124

@dycw

Description

@dycw

Hi, this is a great tutorial!

As I am working through the book, I am trying the reader exercises — it would be great to have some solutions to refer to.

For example, Chapter 1.3 suggests one use a BufReader, so I have an attempt:

use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;

use clap::Parser;

#[derive(Parser)]
struct Cli {
    pattern: String,
    #[clap(parse(from_os_str))]
    path: std::path::PathBuf,
}

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

    println!(
        "You parsed pattern = {:?}, path = {:?}",
        &args.pattern, &args.path
    );

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

    for line in f.by_ref().lines() {
        if line.as_ref().unwrap().contains(&args.pattern) {
            println!("{}", line.as_ref().unwrap());
        }
    }
}

Now I'd like to see how to improve this.

Have I merely missed this somewhere in the book?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions