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::new 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-24, we’ve reproduced the implementation of the Config::new 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 filename: String,
  7. pub case_sensitive: bool,
  8. }
  9. impl Config {
  10. pub fn new(args: &[String]) -> Result<Config, &str> {
  11. if args.len() < 3 {
  12. return Err("not enough arguments");
  13. }
  14. let query = args[1].clone();
  15. let filename = args[2].clone();
  16. let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
  17. Ok(Config {
  18. query,
  19. filename,
  20. case_sensitive,
  21. })
  22. }
  23. }
  24. pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
  25. let contents = fs::read_to_string(config.filename)?;
  26. let results = if config.case_sensitive {
  27. search(&config.query, &contents)
  28. } else {
  29. search_case_insensitive(&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-24: Reproduction of the Config::new 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 new 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 new 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::new function is doing because the iterator will access the values.

Once Config::new 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::new(&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 change the start of the main function that we had in Listing 12-24 to the code in Listing 13-25. This won’t compile until we update Config::new 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::new(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-25: Passing the return value of env::args to Config::new

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

Next, we need to update the definition of Config::new. In your I/O project’s src/lib.rs file, let’s change the signature of Config::new to look like Listing 13-26. 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 filename: String,
  7. pub case_sensitive: bool,
  8. }
  9. impl Config {
  10. pub fn new(mut args: env::Args) -> Result<Config, &'static str> {
  11. // --snip--
  12. if args.len() < 3 {
  13. return Err("not enough arguments");
  14. }
  15. let query = args[1].clone();
  16. let filename = args[2].clone();
  17. let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
  18. Ok(Config {
  19. query,
  20. filename,
  21. case_sensitive,
  22. })
  23. }
  24. }
  25. pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
  26. let contents = fs::read_to_string(config.filename)?;
  27. let results = if config.case_sensitive {
  28. search(&config.query, &contents)
  29. } else {
  30. search_case_insensitive(&config.query, &contents)
  31. };
  32. for line in results {
  33. println!("{}", line);
  34. }
  35. Ok(())
  36. }
  37. pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
  38. let mut results = Vec::new();
  39. for line in contents.lines() {
  40. if line.contains(query) {
  41. results.push(line);
  42. }
  43. }
  44. results
  45. }
  46. pub fn search_case_insensitive<'a>(
  47. query: &str,
  48. contents: &'a str,
  49. ) -> Vec<&'a str> {
  50. let query = query.to_lowercase();
  51. let mut results = Vec::new();
  52. for line in contents.lines() {
  53. if line.to_lowercase().contains(&query) {
  54. results.push(line);
  55. }
  56. }
  57. results
  58. }
  59. #[cfg(test)]
  60. mod tests {
  61. use super::*;
  62. #[test]
  63. fn case_sensitive() {
  64. let query = "duct";
  65. let contents = "\
  66. Rust:
  67. safe, fast, productive.
  68. Pick three.
  69. Duct tape.";
  70. assert_eq!(vec!["safe, fast, productive."], search(query, contents));
  71. }
  72. #[test]
  73. fn case_insensitive() {
  74. let query = "rUsT";
  75. let contents = "\
  76. Rust:
  77. safe, fast, productive.
  78. Pick three.
  79. Trust me.";
  80. assert_eq!(
  81. vec!["Rust:", "Trust me."],
  82. search_case_insensitive(query, contents)
  83. );
  84. }
  85. }

Listing 13-26: Updating the signature of Config::new 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. We’ve updated the signature of the Config::new function so the parameter args has the type std::env::Args instead of &[String]. 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.

We also needed to specify that the string slice error type can now only have the 'static lifetime. Because we’re only ever returning string literals, this was true before. However, when we had a reference in the parameters, there was the possibility that the reference in the return type could have had the same lifetime as the reference in the parameters. The rules that we discussed in the “Lifetime Elision” section of Chapter 10 applied, and we weren’t required to annotate the lifetime of &str. With the change to args, the lifetime elision rules no longer apply, and we must specify the 'static lifetime.

Using Iterator Trait Methods Instead of Indexing

Next, we’ll fix the body of Config::new. The standard library documentation also mentions that std::env::Args implements the Iterator trait, so we know we can call the next method on it! Listing 13-27 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 filename: String,
  7. pub case_sensitive: bool,
  8. }
  9. impl Config {
  10. pub fn new(mut args: env::Args) -> Result<Config, &'static str> {
  11. args.next();
  12. let query = match args.next() {
  13. Some(arg) => arg,
  14. None => return Err("Didn't get a query string"),
  15. };
  16. let filename = match args.next() {
  17. Some(arg) => arg,
  18. None => return Err("Didn't get a file name"),
  19. };
  20. let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
  21. Ok(Config {
  22. query,
  23. filename,
  24. case_sensitive,
  25. })
  26. }
  27. }
  28. pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
  29. let contents = fs::read_to_string(config.filename)?;
  30. let results = if config.case_sensitive {
  31. search(&config.query, &contents)
  32. } else {
  33. search_case_insensitive(&config.query, &contents)
  34. };
  35. for line in results {
  36. println!("{}", line);
  37. }
  38. Ok(())
  39. }
  40. pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
  41. let mut results = Vec::new();
  42. for line in contents.lines() {
  43. if line.contains(query) {
  44. results.push(line);
  45. }
  46. }
  47. results
  48. }
  49. pub fn search_case_insensitive<'a>(
  50. query: &str,
  51. contents: &'a str,
  52. ) -> Vec<&'a str> {
  53. let query = query.to_lowercase();
  54. let mut results = Vec::new();
  55. for line in contents.lines() {
  56. if line.to_lowercase().contains(&query) {
  57. results.push(line);
  58. }
  59. }
  60. results
  61. }
  62. #[cfg(test)]
  63. mod tests {
  64. use super::*;
  65. #[test]
  66. fn case_sensitive() {
  67. let query = "duct";
  68. let contents = "\
  69. Rust:
  70. safe, fast, productive.
  71. Pick three.
  72. Duct tape.";
  73. assert_eq!(vec!["safe, fast, productive."], search(query, contents));
  74. }
  75. #[test]
  76. fn case_insensitive() {
  77. let query = "rUsT";
  78. let contents = "\
  79. Rust:
  80. safe, fast, productive.
  81. Pick three.
  82. Trust me.";
  83. assert_eq!(
  84. vec!["Rust:", "Trust me."],
  85. search_case_insensitive(query, contents)
  86. );
  87. }
  88. }

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

Listing 13-29: 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-19, 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.

The next logical question is which style you should choose in your own code and why: the original implementation in Listing 13-28 or the version using iterators in Listing 13-29. 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.