学习Rust的第22天:mini_grep第2部分

书接上文,在本文中,我们学习了如何通过将 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 the Error 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 and file, both of type String.
    定义一个名为 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 new Config instance.
    定义一个构造函数方法 new 用于创建新的 Config 实例。
  • Takes a slice of strings (&[String]) representing command-line arguments as input.
    将表示命令行参数的字符串片段 ( &[String] ) 作为输入。
  • Returns a Result where Ok contains a Config instance if arguments are sufficient, and Err 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!(&#
  • 9
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老父亲的能量嘎嘣脆

感谢支持,共同成长

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值