@@ -5,8 +5,7 @@ use std::fs;
5
5
use std:: process;
6
6
7
7
fn main ( ) {
8
- let args: Vec < String > = env:: args ( ) . collect ( ) ;
9
- let config = Config :: build ( & args) . unwrap_or_else ( |e| {
8
+ let config = Config :: build ( env:: args ( ) ) . unwrap_or_else ( |e| {
10
9
eprintln ! ( "Problem parsing args: {e}" ) ;
11
10
process:: exit ( 1 ) ;
12
11
} ) ;
@@ -18,14 +17,12 @@ fn main() {
18
17
19
18
fn run ( config : Config ) -> Result < ( ) , Box < dyn Error > > {
20
19
let contents = fs:: read_to_string ( config. file_path ) ?;
21
- let results = if config. ignore_case {
22
- search_case_insensitive ( & config. query , & contents)
20
+ let print = |line| println ! ( "{line}" ) ;
21
+ if config. ignore_case {
22
+ search_case_insensitive ( & config. query , & contents) . for_each ( print) ;
23
23
} else {
24
- search ( & config. query , & contents)
24
+ search ( & config. query , & contents) . for_each ( print ) ;
25
25
} ;
26
- for line in results {
27
- println ! ( "{line}" )
28
- }
29
26
Ok ( ( ) )
30
27
}
31
28
@@ -36,12 +33,16 @@ struct Config {
36
33
}
37
34
38
35
impl Config {
39
- fn build ( args : & [ String ] ) -> Result < Config , & ' static str > {
40
- if args. len ( ) < 3 {
41
- return Err ( "not enough args!" ) ;
42
- }
43
- let query = args[ 1 ] . clone ( ) ;
44
- let file_path = args[ 2 ] . clone ( ) ;
36
+ fn build ( mut args : impl Iterator < Item = String > ) -> Result < Config , & ' static str > {
37
+ args. next ( ) ;
38
+ let query = match args. next ( ) {
39
+ Some ( arg) => arg,
40
+ None => return Err ( "Didn't get a query string" ) ,
41
+ } ;
42
+ let file_path = match args. next ( ) {
43
+ Some ( arg) => arg,
44
+ None => return Err ( "Didn't get a file path" ) ,
45
+ } ;
45
46
let ignore_case = env:: var ( "IGNORE_CASE" ) . is_ok ( ) ;
46
47
Ok ( Config {
47
48
query,
0 commit comments