Skip to content

Commit 524e879

Browse files
committed
分离代码到库包中
1 parent b43ba1f commit 524e879

File tree

2 files changed

+31
-30
lines changed

2 files changed

+31
-30
lines changed

rustybook/minigrep/src/lib.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
use std::error::Error;
2+
use std::fs;
3+
pub struct Config {
4+
pub query: String,
5+
pub file_path: String,
6+
}
7+
8+
impl Config {
9+
pub fn build(args: &[String]) -> Result<Config, &'static str> {
10+
if args.len() < 3 {
11+
return Err("not enough arguments");
12+
}
13+
14+
let query = args[1].clone();
15+
let file_path = args[2].clone();
16+
17+
Ok(Config { query, file_path })
18+
}
19+
}
20+
21+
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
22+
let contents =
23+
fs::read_to_string(config.file_path).expect("Should have been able to read the file");
24+
25+
println!("With text:\n{contents}");
26+
27+
Ok(())
28+
}

rustybook/minigrep/src/main.rs

Lines changed: 3 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use std::env;
2-
use std::error::Error;
3-
use std::fs;
42
use std::process;
53

4+
use minigrep::Config;
5+
66
fn main() {
77
let args: Vec<String> = env::args().collect();
88

@@ -15,35 +15,8 @@ fn main() {
1515
println!("Searching for {}", config.query);
1616
println!("In file {}", config.file_path);
1717

18-
if let Err(e) = run(config) {
18+
if let Err(e) = minigrep::run(config) {
1919
println!("Application error: {e}");
2020
process::exit(1);
2121
}
2222
}
23-
24-
fn run(config: Config) -> Result<(), Box<dyn Error>> {
25-
let contents =
26-
fs::read_to_string(config.file_path).expect("Should have been able to read the file");
27-
28-
println!("With text:\n{contents}");
29-
30-
Ok(())
31-
}
32-
33-
struct Config {
34-
query: String,
35-
file_path: String,
36-
}
37-
38-
impl Config {
39-
fn build(args: &[String]) -> Result<Config, &'static str> {
40-
if args.len() < 3 {
41-
return Err("not enough arguments");
42-
}
43-
44-
let query = args[1].clone();
45-
let file_path = args[2].clone();
46-
47-
Ok(Config { query, file_path })
48-
}
49-
}

0 commit comments

Comments
 (0)