]> git.proxmox.com Git - rustc.git/blob - src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/src/main.rs
New upstream version 1.50.0+dfsg1
[rustc.git] / src / doc / book / listings / ch12-an-io-project / no-listing-01-handling-errors-in-main / src / main.rs
1 use std::env;
2 use std::error::Error;
3 use std::fs;
4 use std::process;
5
6 // ANCHOR: here
7 fn main() {
8 // --snip--
9
10 // ANCHOR_END: here
11 let args: Vec<String> = env::args().collect();
12
13 let config = Config::new(&args).unwrap_or_else(|err| {
14 println!("Problem parsing arguments: {}", err);
15 process::exit(1);
16 });
17
18 // ANCHOR: here
19 println!("Searching for {}", config.query);
20 println!("In file {}", config.filename);
21
22 if let Err(e) = run(config) {
23 println!("Application error: {}", e);
24
25 process::exit(1);
26 }
27 }
28 // ANCHOR_END: here
29
30 fn run(config: Config) -> Result<(), Box<dyn Error>> {
31 let contents = fs::read_to_string(config.filename)?;
32
33 println!("With text:\n{}", contents);
34
35 Ok(())
36 }
37
38 struct Config {
39 query: String,
40 filename: String,
41 }
42
43 impl Config {
44 fn new(args: &[String]) -> Result<Config, &str> {
45 if args.len() < 3 {
46 return Err("not enough arguments");
47 }
48
49 let query = args[1].clone();
50 let filename = args[2].clone();
51
52 Ok(Config { query, filename })
53 }
54 }