Skip to content

Commit c9acfb3

Browse files
committed
add use of iterators
1 parent 6d83b93 commit c9acfb3

File tree

2 files changed

+18
-18
lines changed

2 files changed

+18
-18
lines changed

src/lib.rs

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,18 @@ pub struct Config {
77
}
88

99
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();
10+
pub fn build(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
11+
args.next(); // First value in args is just the name of the program
12+
13+
let query = match args.next() {
14+
Some(arg) => arg,
15+
_none => return Err("Didn't get a query String!"),
16+
};
17+
let file_path = match args.next() {
18+
Some(arg) => arg,
19+
_none => return Err("Didn't get a file path!")
20+
};
21+
1622
let ignore_case = env::var("IGNORE_CASE").is_ok();
1723

1824
Ok(Config {
@@ -37,14 +43,9 @@ pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
3743
}
3844

3945
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
40-
let mut results: Vec<&str> = Vec::new();
41-
42-
for line in contents.lines() {
43-
if line.contains(query) {
44-
results.push(line);
45-
}
46-
}
47-
results
46+
contents.lines()
47+
.filter(|line| line.contains(query))
48+
.collect()
4849
}
4950

5051
pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {

src/main.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,14 @@ use minigrep::run;
44
use minigrep::Config;
55

66
fn main() {
7-
let args: Vec<String> = env::args().collect();
87

9-
let config = Config::build(&args).unwrap_or_else(|err| {
8+
let config = Config::build(env::args()).unwrap_or_else(|err| {
109
eprintln!("Problem parsing arguments: {}", err);
1110
process::exit(1);
1211
});
1312

14-
println!("Searching for {}", config.query);
15-
println!("In file {}\n", config.file_path);
13+
println!("Searching for \"{}\"", config.query);
14+
println!("In file \"{}\"\n", config.file_path);
1615

1716
if let Err(e) = run(config) {
1817
eprintln!("Application error: {}", e);

0 commit comments

Comments
 (0)