书接上文,在本文中,我们学习了如何通过将 Rust 程序的逻辑移至单独的库箱中并采用测试驱动开发 (TDD) 实践来重构 Rust 程序。通过在实现功能之前编写测试,我们确保了代码的可靠性。我们涵盖了基本的 Rust 概念,例如错误处理、环境变量和命令行参数。本文最后提出了最后一个改进:将错误消息重定向到 stderr 以提供更好的用户体验。
Recap 回顾
This is our code so far
这是我们到目前为止的代码
use std::env;
use std::fs;
use std::process;
use std::error::Error;
struct Config {
query: String,
file: String,
}
impl Config{
fn new(args: &[String]) -> Result<Config, &str>{
if args.len() < 3{
return Err("Not enough arguments.");
}
let query: String = args[1].clone();
let file: String = args[2].clone();
Ok(Config{query,file})
}
}
fn run(config: Config) -> Result<(), Box<dyn Error>>{
let contents = fs::read_to_string(config.file)?;
println!("file contents: {}",contents);
Ok(())
}
fn main(){
let args: Vec<String> = env::args().collect();
let config = Config::new(&args).unwrap_or_else(|err|{
println!("Problem parsing arguments: {}",err);
println!("Expected: {} search_query filename", args[0]);
process::exit(1);
});
if let Err(e) = run(config) {
println!("Application error: {}",e);
process::exit(1);
}
}
Explanation: 解释:
use std::env;
use std::fs;
use std::process;
use std::error::Error;
These lines import specific modules from the standard library (std
).
这些行从标准库 ( std
) 导入特定模块。
env
: Provides functions for interacting with the environment (e.g., command-line arguments).env
:提供与环境交互的函数(例如命令行参数)。fs
: Offers file system operations like reading and writing files.fs
:提供文件系统操作,例如读取和写入文件。process
: Provides functions for interacting with processes (e.g., exiting a process).process
:提供与进程交互的功能(例如,退出进程)。error::Error
: Imports theError
trait, which is used for error handling.error::Error
:导入Error
特征,用于错误处理。
struct Config {
query: String,
file: String,
}
- Defines a struct named
Config
with two fields:query
andfile
, both of typeString
.
定义一个名为Config
的结构体,其中包含两个字段:query
和file
,均为String
类型。
impl Config{
fn new(args: &[String]) -> Result<Config, &str>{
if args.len() < 3 {
return Err("Not enough arguments.");
}
let query: String = args[1].clone();
let file: String = args[2].clone();
Ok(Config{query, file})
}
}
Implements methods for the Config
struct.
实现 Config
结构的方法。
- Defines a constructor method
new
for creating a newConfig
instance.
定义一个构造函数方法new
用于创建新的Config
实例。 - Takes a slice of strings (
&[String]
) representing command-line arguments as input.
将表示命令行参数的字符串片段 (&[String]
) 作为输入。 - Returns a
Result
whereOk
contains aConfig
instance if arguments are sufficient, andErr
contains an error message otherwise.
如果参数足够,则返回Result
,其中Ok
包含Config
实例,否则Err
包含错误消息。
fn run(config: Config) -> Result<(), Box<dyn Error>>{
let contents = fs::read_to_string(config.file)?;
println!(&#