mirror of
https://github.com/gnu4cn/rust-lang-zh_CN.git
synced 2026-08-19 12:43:28 +08:00
Updated 'src/io_project/refactoring.md'.
This commit is contained in:
@@ -1,18 +1,42 @@
|
||||
use std::{env, fs};
|
||||
use std::{env, fs, process, error::Error};
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
|
||||
let query = &args[1];
|
||||
let file_path = &args[2];
|
||||
let config = Config::build(&args).unwrap_or_else(|err| {
|
||||
println! ("解析参数时遇到问题:{err}");
|
||||
process::exit(1);
|
||||
});
|
||||
|
||||
println! ("
|
||||
在文件 {file_path} 中
|
||||
检索 {query}
|
||||
");
|
||||
在文件 {} 中
|
||||
检索 {}", config.file_path, config.query);
|
||||
|
||||
let contents = fs::read_to_string(file_path)
|
||||
.expect("应该已经能够读取文件");
|
||||
|
||||
println! ("带有文本:\n{contents}");
|
||||
run(config);
|
||||
}
|
||||
|
||||
fn run(config: Config) -> Result<(), Box<dyn Error>>{
|
||||
let contents = fs::read_to_string(config.file_path)?;
|
||||
|
||||
println! ("有着文本:\n{contents}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Config {
|
||||
query: String,
|
||||
file_path: String,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
fn build(args: &[String]) -> Result<Config, &'static str> {
|
||||
if args.len() < 3 {
|
||||
return Err("参数不足");
|
||||
}
|
||||
|
||||
let query = args[1].clone();
|
||||
let file_path = args[2].clone();
|
||||
|
||||
Ok(Config { query, file_path })
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user