trpl-zh-cn/listings/ch12-an-io-project/listing-12-14/src/lib.rs

29 lines
579 B
Rust
Raw Normal View History

2022-02-06 16:43:51 +08:00
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
2023-01-16 17:34:52 +08:00
pub file_path: String,
2022-02-06 16:43:51 +08:00
}
impl Config {
2023-01-16 17:34:52 +08:00
pub 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
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
2023-01-16 17:34:52 +08:00
let contents = fs::read_to_string(config.file_path)?;
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
Ok(())
}