Improving Our I/O Project

With this new knowledge about iterators, we can improve the I/O project in Chapter 12 by using iterators to make places in the code clearer and more concise. Let’s look at how iterators can improve our implementation of the Config::build function and the search function.

Removing a clone Using an Iterator

In Listing 12-6, we added code that took a slice of String values and created an instance of the Config struct by indexing into the slice and cloning the values, allowing the Config struct to own those values. In Listing 13-17, we’ve reproduced the implementation of the Config::build function as it was in Listing 12-23:

Filename: src/lib.rs

  1. use std::env;
  2. use std::error::Error;
  3. use std::fs;
  4. pub struct Config {
  5. pub query: String,
  6. pub file_path: String,
  7. pub ignore_case: bool,
  8. }
  9. impl Config {
  10. pub fn build(args: &[String]) -> Result<Config, &'static str> {
  11. if args.len() < 3 {
  12. return Err("not enough arguments");
  13. }
  14. let query = args[1].clone();
  15. let file_path = args[2].clone();
  16. let ignore_case = env::var("IGNORE_CASE").is_ok();
  17. Ok(Config {
  18. query,
  19. file_path,
  20. ignore_case,
  21. })
  22. }
  23. }
  24. pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
  25. let contents = fs::read_to_string(config.file_path)?;
  26. let results = if config.ignore_case {
  27. search_case_insensitive(&config.query, &contents)
  28. } else {
  29. search(&config.query, &contents)
  30. };
  31. for line in results {
  32. println!("{line}");
  33. }
  34. Ok(())
  35. }
  36. pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
  37. let mut results = Vec::new();
  38. for line in contents.lines() {
  39. if line.contains(query) {
  40. results.push(line);
  41. }
  42. }
  43. results
  44. }
  45. pub fn search_case_insensitive<'a>(
  46. query: &str,
  47. contents: &'a str,
  48. ) -> Vec<&'a str> {
  49. let query = query.to_lowercase();
  50. let mut results = Vec::new();
  51. for line in contents.lines() {
  52. if line.to_lowercase().contains(&query) {
  53. results.push(line);
  54. }
  55. }
  56. results
  57. }
  58. #[cfg(test)]
  59. mod tests {
  60. use super::*;
  61. #[test]
  62. fn case_sensitive() {
  63. let query = "duct";
  64. let contents = "\
  65. Rust:
  66. safe, fast, productive.
  67. Pick three.
  68. Duct tape.";
  69. assert_eq!(vec!["safe, fast, productive."], search(query, contents));
  70. }
  71. #[test]
  72. fn case_insensitive() {
  73. let query = "rUsT";
  74. let contents = "\
  75. Rust:
  76. safe, fast, productive.
  77. Pick three.
  78. Trust me.";
  79. assert_eq!(
  80. vec!["Rust:", "Trust me."],
  81. search_case_insensitive(query, contents)
  82. );
  83. }
  84. }

Listing 13-17: Reproduction of the Config::build function from Listing 12-23

At the time, we said not to worry about the inefficient clone calls because we would remove them in the future. Well, that time is now!

We needed clone here because we have a slice with String elements in the parameter args, but the build function doesn’t own args. To return ownership of a Config instance, we had to clone the values from the query and filename fields of Config so the Config instance can own its values.

With our new knowledge about iterators, we can change the build function to take ownership of an iterator as its argument instead of borrowing a slice. We’ll use the iterator functionality instead of the code that checks the length of the slice and indexes into specific locations. This will clarify what the Config::build function is doing because the iterator will access the values.

Once Config::build takes ownership of the iterator and stops using indexing operations that borrow, we can move the String values from the iterator into Config rather than calling clone and making a new allocation.

Using the Returned Iterator Directly

Open your I/O project’s src/main.rs file, which should look like this:

Filename: src/main.rs

  1. use std::env;
  2. use std::process;
  3. use minigrep::Config;
  4. fn main() {
  5. let args: Vec<String> = env::args().collect();
  6. let config = Config::build(&args).unwrap_or_else(|err| {
  7. eprintln!("Problem parsing arguments: {err}");
  8. process::exit(1);
  9. });
  10. // --snip--
  11. if let Err(e) = minigrep::run(config) {
  12. eprintln!("Application error: {e}");
  13. process::exit(1);
  14. }
  15. }

We’ll first change the start of the main function that we had in Listing 12-24 to the code in Listing 13-18, which this time uses an iterator. This won’t compile until we update Config::build as well.

Filename: src/main.rs

  1. use std::env;
  2. use std::process;
  3. use minigrep::Config;
  4. fn main() {
  5. let config = Config::build(env::args()).unwrap_or_else(|err| {
  6. eprintln!("Problem parsing arguments: {err}");
  7. process::exit(1);
  8. });
  9. // --snip--
  10. if let Err(e) = minigrep::run(config) {
  11. eprintln!("Application error: {e}");
  12. process::exit(1);
  13. }
  14. }

Listing 13-18: Passing the return value of env::args to Config::build

The env::args function returns an iterator! Rather than collecting the iterator values into a vector and then passing a slice to Config::build, now we’re passing ownership of the iterator returned from env::args to Config::build directly.

Next, we need to update the definition of Config::build. In your I/O project’s src/lib.rs file, let’s change the signature of Config::build to look like Listing 13-19. This still won’t compile because we need to update the function body.

Filename: src/lib.rs

  1. use std::env;
  2. use std::error::Error;
  3. use std::fs;
  4. pub struct Config {
  5. pub query: String,
  6. pub file_path: String,
  7. pub ignore_case: bool,
  8. }
  9. impl Config {
  10. pub fn build(
  11. mut args: impl Iterator<Item = String>,
  12. ) -> Result<Config, &'static str> {
  13. // --snip--
  14. if args.len() < 3 {
  15. return Err("not enough arguments");
  16. }
  17. let query = args[1].clone();
  18. let file_path = args[2].clone();
  19. let ignore_case = env::var("IGNORE_CASE").is_ok();
  20. Ok(Config {
  21. query,
  22. file_path,
  23. ignore_case,
  24. })
  25. }
  26. }
  27. pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
  28. let contents = fs::read_to_string(config.file_path)?;
  29. let results = if config.ignore_case {
  30. search_case_insensitive(&config.query, &contents)
  31. } else {
  32. search(&config.query, &contents)
  33. };
  34. for line in results {
  35. println!("{line}");
  36. }
  37. Ok(())
  38. }
  39. pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
  40. let mut results = Vec::new();
  41. for line in contents.lines() {
  42. if line.contains(query) {
  43. results.push(line);
  44. }
  45. }
  46. results
  47. }
  48. pub fn search_case_insensitive<'a>(
  49. query: &str,
  50. contents: &'a str,
  51. ) -> Vec<&'a str> {
  52. let query = query.to_lowercase();
  53. let mut results = Vec::new();
  54. for line in contents.lines() {
  55. if line.to_lowercase().contains(&query) {
  56. results.push(line);
  57. }
  58. }
  59. results
  60. }
  61. #[cfg(test)]
  62. mod tests {
  63. use super::*;
  64. #[test]
  65. fn case_sensitive() {
  66. let query = "duct";
  67. let contents = "\
  68. Rust:
  69. safe, fast, productive.
  70. Pick three.
  71. Duct tape.";
  72. assert_eq!(vec!["safe, fast, productive."], search(query, contents));
  73. }
  74. #[test]
  75. fn case_insensitive() {
  76. let query = "rUsT";
  77. let contents = "\
  78. Rust:
  79. safe, fast, productive.
  80. Pick three.
  81. Trust me.";
  82. assert_eq!(
  83. vec!["Rust:", "Trust me."],
  84. search_case_insensitive(query, contents)
  85. );
  86. }
  87. }

Listing 13-19: Updating the signature of Config::build to expect an iterator

The standard library documentation for the env::args function shows that the type of the iterator it returns is std::env::Args, and that type implements the Iterator trait and returns String values.

We’ve updated the signature of the Config::build function so the parameter args has a generic type with the trait bounds impl Iterator instead of &[String]. This usage of the impl Trait syntax we discussed in the “Traits as Parameters” section of Chapter 10 means that args can be any type that implements the Iterator type and returns String items.

Because we’re taking ownership of args and we’ll be mutating args by iterating over it, we can add the mut keyword into the specification of the args parameter to make it mutable.

Using Iterator Trait Methods Instead of Indexing

Next, we’ll fix the body of Config::build. Because args implements the Iterator trait, we know we can call the next method on it! Listing 13-20 updates the code from Listing 12-23 to use the next method:

Filename: src/lib.rs

  1. use std::env;
  2. use std::error::Error;
  3. use std::fs;
  4. pub struct Config {
  5. pub query: String,
  6. pub file_path: String,
  7. pub ignore_case: bool,
  8. }
  9. impl Config {
  10. pub fn build(
  11. mut args: impl Iterator<Item = String>,
  12. ) -> Result<Config, &'static str> {
  13. args.next();
  14. let query = match args.next() {
  15. Some(arg) => arg,
  16. None => return Err("Didn't get a query string"),
  17. };
  18. let file_path = match args.next() {
  19. Some(arg) => arg,
  20. None => return Err("Didn't get a file path"),
  21. };
  22. let ignore_case = env::var("IGNORE_CASE").is_ok();
  23. Ok(Config {
  24. query,
  25. file_path,
  26. ignore_case,
  27. })
  28. }
  29. }
  30. pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
  31. let contents = fs::read_to_string(config.file_path)?;
  32. let results = if config.ignore_case {
  33. search_case_insensitive(&config.query, &contents)
  34. } else {
  35. search(&config.query, &contents)
  36. };
  37. for line in results {
  38. println!("{line}");
  39. }
  40. Ok(())
  41. }
  42. pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
  43. let mut results = Vec::new();
  44. for line in contents.lines() {
  45. if line.contains(query) {
  46. results.push(line);
  47. }
  48. }
  49. results
  50. }
  51. pub fn search_case_insensitive<'a>(
  52. query: &str,
  53. contents: &'a str,
  54. ) -> Vec<&'a str> {
  55. let query = query.to_lowercase();
  56. let mut results = Vec::new();
  57. for line in contents.lines() {
  58. if line.to_lowercase().contains(&query) {
  59. results.push(line);
  60. }
  61. }
  62. results
  63. }
  64. #[cfg(test)]
  65. mod tests {
  66. use super::*;
  67. #[test]
  68. fn case_sensitive() {
  69. let query = "duct";
  70. let contents = "\
  71. Rust:
  72. safe, fast, productive.
  73. Pick three.
  74. Duct tape.";
  75. assert_eq!(vec!["safe, fast, productive."], search(query, contents));
  76. }
  77. #[test]
  78. fn case_insensitive() {
  79. let query = "rUsT";
  80. let contents = "\
  81. Rust:
  82. safe, fast, productive.
  83. Pick three.
  84. Trust me.";
  85. assert_eq!(
  86. vec!["Rust:", "Trust me."],
  87. search_case_insensitive(query, contents)
  88. );
  89. }
  90. }

Listing 13-20: Changing the body of Config::build to use iterator methods

Remember that the first value in the return value of env::args is the name of the program. We want to ignore that and get to the next value, so first we call next and do nothing with the return value. Second, we call next to get the value we want to put in the query field of Config. If next returns a Some, we use a match to extract the value. If it returns None, it means not enough arguments were given and we return early with an Err value. We do the same thing for the filename value.

Making Code Clearer with Iterator Adaptors

We can also take advantage of iterators in the search function in our I/O project, which is reproduced here in Listing 13-21 as it was in Listing 12-19:

Filename: src/lib.rs

  1. use std::error::Error;
  2. use std::fs;
  3. pub struct Config {
  4. pub query: String,
  5. pub file_path: String,
  6. }
  7. impl Config {
  8. pub fn build(args: &[String]) -> Result<Config, &'static str> {
  9. if args.len() < 3 {
  10. return Err("not enough arguments");
  11. }
  12. let query = args[1].clone();
  13. let file_path = args[2].clone();
  14. Ok(Config { query, file_path })
  15. }
  16. }
  17. pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
  18. let contents = fs::read_to_string(config.file_path)?;
  19. Ok(())
  20. }
  21. pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
  22. let mut results = Vec::new();
  23. for line in contents.lines() {
  24. if line.contains(query) {
  25. results.push(line);
  26. }
  27. }
  28. results
  29. }
  30. #[cfg(test)]
  31. mod tests {
  32. use super::*;
  33. #[test]
  34. fn one_result() {
  35. let query = "duct";
  36. let contents = "\
  37. Rust:
  38. safe, fast, productive.
  39. Pick three.";
  40. assert_eq!(vec!["safe, fast, productive."], search(query, contents));
  41. }
  42. }

Listing 13-21: The implementation of the search function from Listing 12-19

We can write this code in a more concise way using iterator adaptor methods. Doing so also lets us avoid having a mutable intermediate results vector. The functional programming style prefers to minimize the amount of mutable state to make code clearer. Removing the mutable state might enable a future enhancement to make searching happen in parallel, because we wouldn’t have to manage concurrent access to the results vector. Listing 13-22 shows this change:

Filename: src/lib.rs

  1. use std::env;
  2. use std::error::Error;
  3. use std::fs;
  4. pub struct Config {
  5. pub query: String,
  6. pub file_path: String,
  7. pub ignore_case: bool,
  8. }
  9. impl Config {
  10. pub fn build(
  11. mut args: impl Iterator<Item = String>,
  12. ) -> Result<Config, &'static str> {
  13. args.next();
  14. let query = match args.next() {
  15. Some(arg) => arg,
  16. None => return Err("Didn't get a query string"),
  17. };
  18. let file_path = match args.next() {
  19. Some(arg) => arg,
  20. None => return Err("Didn't get a file path"),
  21. };
  22. let ignore_case = env::var("IGNORE_CASE").is_ok();
  23. Ok(Config {
  24. query,
  25. file_path,
  26. ignore_case,
  27. })
  28. }
  29. }
  30. pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
  31. let contents = fs::read_to_string(config.file_path)?;
  32. let results = if config.ignore_case {
  33. search_case_insensitive(&config.query, &contents)
  34. } else {
  35. search(&config.query, &contents)
  36. };
  37. for line in results {
  38. println!("{line}");
  39. }
  40. Ok(())
  41. }
  42. pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
  43. contents
  44. .lines()
  45. .filter(|line| line.contains(query))
  46. .collect()
  47. }
  48. pub fn search_case_insensitive<'a>(
  49. query: &str,
  50. contents: &'a str,
  51. ) -> Vec<&'a str> {
  52. let query = query.to_lowercase();
  53. let mut results = Vec::new();
  54. for line in contents.lines() {
  55. if line.to_lowercase().contains(&query) {
  56. results.push(line);
  57. }
  58. }
  59. results
  60. }
  61. #[cfg(test)]
  62. mod tests {
  63. use super::*;
  64. #[test]
  65. fn case_sensitive() {
  66. let query = "duct";
  67. let contents = "\
  68. Rust:
  69. safe, fast, productive.
  70. Pick three.
  71. Duct tape.";
  72. assert_eq!(vec!["safe, fast, productive."], search(query, contents));
  73. }
  74. #[test]
  75. fn case_insensitive() {
  76. let query = "rUsT";
  77. let contents = "\
  78. Rust:
  79. safe, fast, productive.
  80. Pick three.
  81. Trust me.";
  82. assert_eq!(
  83. vec!["Rust:", "Trust me."],
  84. search_case_insensitive(query, contents)
  85. );
  86. }
  87. }

Listing 13-22: Using iterator adaptor methods in the implementation of the search function

Recall that the purpose of the search function is to return all lines in contents that contain the query. Similar to the filter example in Listing 13-16, this code uses the filter adaptor to keep only the lines that line.contains(query) returns true for. We then collect the matching lines into another vector with collect. Much simpler! Feel free to make the same change to use iterator methods in the search_case_insensitive function as well.

Choosing Between Loops or Iterators

The next logical question is which style you should choose in your own code and why: the original implementation in Listing 13-21 or the version using iterators in Listing 13-22. Most Rust programmers prefer to use the iterator style. It’s a bit tougher to get the hang of at first, but once you get a feel for the various iterator adaptors and what they do, iterators can be easier to understand. Instead of fiddling with the various bits of looping and building new vectors, the code focuses on the high-level objective of the loop. This abstracts away some of the commonplace code so it’s easier to see the concepts that are unique to this code, such as the filtering condition each element in the iterator must pass.

But are the two implementations truly equivalent? The intuitive assumption might be that the more low-level loop will be faster. Let’s talk about performance.