trpl-zh-cn/listings/ch12-an-io-project/listing-12-09/src/main.rs

37 lines
773 B
Rust
Raw Normal View History

2022-02-06 16:43:51 +08:00
use std::env;
use std::fs;
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::new(&args);
println!("Searching for {}", config.query);
2023-01-16 17:34:52 +08:00
println!("In file {}", config.file_path);
2022-02-06 16:43:51 +08:00
2023-01-16 17:34:52 +08:00
let contents = fs::read_to_string(config.file_path)
.expect("Should have been able to read the file");
2022-02-06 16:43:51 +08:00
2023-01-16 17:34:52 +08:00
println!("With text:\n{contents}");
2022-02-06 16:43:51 +08:00
}
struct Config {
query: String,
2023-01-16 17:34:52 +08:00
file_path: String,
2022-02-06 16:43:51 +08:00
}
// ANCHOR: here
impl Config {
2023-01-16 17:34:52 +08:00
fn build(args: &[String]) -> Result<Config, &'static str> {
2022-02-06 16:43:51 +08:00
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
2023-01-16 17:34:52 +08:00
let file_path = args[2].clone();
2022-02-06 16:43:51 +08:00
2023-01-16 17:34:52 +08:00
Ok(Config { query, file_path })
2022-02-06 16:43:51 +08:00
}
}
// ANCHOR_END: here