First implementation of grrs

After the last chapter on command line arguments,we have our input data,and we can start to write our actual tool.Our main function only contains this line right now:

  1. let args = Cli::from_args();

Let’s start by opening the file we got.

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

Aside:See that .expect method here?This is a shortcut function to quit that will make the program exit immediatelywhen the value (in this case the input file)could not be read.It’s not very pretty,and in the next chapter on Nicer error reportingwe will look at how to improve this.

Now, let’s iterate over the linesand print each one that contains our pattern:

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

Give it a try: cargo run — main src/main.rs should work now!

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 BufReaderinstead of read_to_string().)