File tree Expand file tree Collapse file tree 2 files changed +18
-18
lines changed Expand file tree Collapse file tree 2 files changed +18
-18
lines changed Original file line number Diff line number Diff line change @@ -7,12 +7,18 @@ pub struct Config {
7
7
}
8
8
9
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 ( ) ;
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
+
16
22
let ignore_case = env:: var ( "IGNORE_CASE" ) . is_ok ( ) ;
17
23
18
24
Ok ( Config {
@@ -37,14 +43,9 @@ pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
37
43
}
38
44
39
45
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 ( )
48
49
}
49
50
50
51
pub fn search_case_insensitive < ' a > ( query : & str , contents : & ' a str ) -> Vec < & ' a str > {
Original file line number Diff line number Diff line change @@ -4,15 +4,14 @@ use minigrep::run;
4
4
use minigrep:: Config ;
5
5
6
6
fn main ( ) {
7
- let args: Vec < String > = env:: args ( ) . collect ( ) ;
8
7
9
- let config = Config :: build ( & args) . unwrap_or_else ( |err| {
8
+ let config = Config :: build ( env :: args ( ) ) . unwrap_or_else ( |err| {
10
9
eprintln ! ( "Problem parsing arguments: {}" , err) ;
11
10
process:: exit ( 1 ) ;
12
11
} ) ;
13
12
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) ;
16
15
17
16
if let Err ( e) = run ( config) {
18
17
eprintln ! ( "Application error: {}" , e) ;
You can’t perform that action at this time.
0 commit comments