跳至主要內容
rust 随笔(三)

rust 随笔(三)

thiserror

这篇文章探讨一个常见的错误处理库——thiserror 首先我们回顾一下上一篇的Error第二种用法:

#[derive(Debug)]
pub enum AppError {
    Config(ConfigError),
    Database(DatabaseError),
    Query(QueryError),
    Io(io::Error), // 有时也可能直接暴露一些通用的 IO 错误
    Initialization(String), // 其他初始化错误
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AppError::Config(err) => write!(f, "{}", err), // 直接调用 ConfigError 的 Display
            AppError::Database(err) => write!(f, "{}", err), // 直接调用 DatabaseError 的 Display
            AppError::Query(err) => write!(f, "{}", err),
            AppError::Io(err) => write!(f, "IO 错误: {}", err),
            AppError::Initialization(msg) => write!(f, "初始化错误: {}", msg),
        }
    }
}

impl Error for AppError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            AppError::Config(err) => Some(err),    // ConfigError 实现了 Error,可以作为 source
            AppError::Database(err) => Some(err),  // DatabaseError 实现了 Error
            AppError::Query(err) => Some(err),     // QueryError 实现了 Error
            AppError::Io(err) => Some(err),        // io::Error 本身就实现了 Error
            AppError::Initialization(_) => None,
        }
    }
}

// 实现 From trait
impl From<ConfigError> for AppError {
    fn from(err: ConfigError) -> Self {
        AppError::Config(err)
    }
}

impl From<DatabaseError> for AppError {
    fn from(err: DatabaseError) -> Self {
        AppError::Database(err)
    }
}

impl From<QueryError> for AppError {
    fn from(err: QueryError) -> Self {
        AppError::Query(err)
    }
}

impl From<io::Error> for AppError { // 有时也希望直接转换IO错误
    fn from(err: io::Error) -> Self {
        AppError::Io(err)
    }
}

Mr.Lexon大约 4 分钟rustrustthiserror
rust 随笔(二)

rust 随笔(二)

这篇文章探讨在Rust中自定义Error如何设计,我们先直接给出一个例子:

use std::fmt;

#[derive(Debug)]
enum CustomError {
    CustomErrorKind1,
    CustomErrorKind2(String),
    CustomErrorKind3(String, String),
}
//实现Display,用于呈现错误结构
impl fmt::Display for CustomError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CustomError::CustomErrorKind1 => write!(f, "Custom Error Type 1 Occurred"),
            CustomError::CustomErrorKind2(s) => write!(f, "Custom Error Type 2 Occurred: {}", s),
            CustomError::CustomErrorKind3(s1, s2) => write!(f, "Custom Error Type 3 Occurred: {} - {}", s1, s2),
        }
    }
}

//通用化
impl std::error::Error for CustomError {}

// Example of how to use it:
fn main() {
    let error1 = CustomError::CustomErrorKind1;
    let error2 = CustomError::CustomErrorKind2("Something went wrong".to_string());
    let error3 = CustomError::CustomErrorKind3("File not found".to_string(), "Ensure the path is correct".to_string());

    println!("{}", error1);
    println!("{}", error2);
    println!("{}", error3);

    // For debug formatting
    println!("{:?}", error1);
    println!("{:?}", error2);
    println!("{:?}", error3);
}

Mr.Lexon大约 8 分钟rustrust
rust随笔(一)

rust随笔(一)

最近将《the book》看到了闭包部分,感触良多,发现rust的设计其实和oop关系不大,并且“组合优于继承”这句话不仅仅只是和结构体说的,还是对函数说的。本篇探讨一下问题:

  1. 何为生命周期
  2. rust和代码整洁之道有什么关系
  3. 为什么说学好组合子就学会了rust基本思想了

何为生命周期

我这里不从具体的函数定义出发,我从闭包出发,在定义中,闭包有以下trait

trait Fn;
trait FnOnce;
trait FnMut;

Mr.Lexon大约 14 分钟rustrustfunctional-program
rust基础笔记

rust基础笔记

所有权

rust区别于其他编程语言来说,它新增了一个概念叫所有权,就是变量的移动是有所有权概念的,什么意思呢,如下代码:

let a = 10;
let b = a;
foo(a)

Mr.Lexon大约 3 分钟rustrust
rust问题记录

rust问题记录

crate版本问题

如果在安装依赖的时候出现:

error: package `xxx` cannot be built because it requires rustc 1.81.0 or newer, while the currently active rustc version is 1.77.1
Either upgrade to rustc 1.81.0 or newer, or use
cargo update parse-size@1.1.0 --precise ver
where `ver` is the latest version of `parse-size` supporting rustc 1.77.1

Mr.Lexon小于 1 分钟rustrust