[rustlings]13_error_handling

errors6

这一个就是在Err(E)中加了点手脚,就是Err(E)中E的类型也是一个Err类型.

这里是创建了一个新的Err类型,Err类型中有两种不同的枚举值.对于不同的枚举值代表两种不同的错误.

复制代码
// Using catch-all error types like `Box<dyn Error>` isn't recommended for
// library code where callers might want to make decisions based on the error
// content instead of printing it out or propagating it further. Here, we define
// a custom error type to make it possible for callers to decide what to do next
// when our function returns an error.

use std::num::ParseIntError;

#[derive(PartialEq, Debug)]
enum CreationError {
    Negative,
    Zero,
}

// A custom error type that we will be using in `PositiveNonzeroInteger::parse`.
#[derive(PartialEq, Debug)]
enum ParsePosNonzeroError {
    Creation(CreationError),
    ParseInt(ParseIntError),
}

impl ParsePosNonzeroError {
    fn from_creation(err: CreationError) -> Self {
        Self::Creation(err)
    }

    // TODO: Add another error conversion function here.
    // fn from_parseint(???) -> Self { ??? }
    fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError{
        ParsePosNonzeroError::ParseInt(err)
    }
}

#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);

impl PositiveNonzeroInteger {
    fn new(value: i64) -> Result<Self, CreationError> {
        match value {
            x if x < 0 => Err(CreationError::Negative),
            0 => Err(CreationError::Zero),
            x => Ok(Self(x as u64)),
        }
    }

    fn parse(s: &str) -> Result<Self, ParsePosNonzeroError> {
        // TODO: change this to return an appropriate error instead of panicking
        // when `parse()` returns an error.
        let x: i64 = match s.parse(){
            Ok(t) => t,
            Err(e) => {
                return Err(ParsePosNonzeroError::from_parseint(e));
            },
        };
        Self::new(x).map_err(ParsePosNonzeroError::from_creation)
    }
}

fn main() {
    // You can optionally experiment here.
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_parse_error() {
        assert!(matches!(
            PositiveNonzeroInteger::parse("not a number"),
            Err(ParsePosNonzeroError::ParseInt(_)),
        ));
    }

    #[test]
    fn test_negative() {
        assert_eq!(
            PositiveNonzeroInteger::parse("-555"),
            Err(ParsePosNonzeroError::Creation(CreationError::Negative)),
        );
    }

    #[test]
    fn test_zero() {
        assert_eq!(
            PositiveNonzeroInteger::parse("0"),
            Err(ParsePosNonzeroError::Creation(CreationError::Zero)),
        );
    }

    #[test]
    fn test_positive() {
        let x = PositiveNonzeroInteger::new(42).unwrap();
        assert_eq!(x.0, 42);
        assert_eq!(PositiveNonzeroInteger::parse("42"), Ok(x));
    }
}
相关推荐
会头痛的可达鸭5 小时前
Reqwest 库详细使用指南
http·rust·reqwest
mzhan0179 小时前
Rust 资料
开发语言·后端·rust
Hello.Reader10 小时前
Rocket 0.5 快速上手从克隆仓库到跑起第一个示例
rust·rocket
HelloReader11 小时前
一款“既好玩又靠谱”的 Rust Web 框架
后端·rust
HelloReader11 小时前
从 Rocket 0.4 升级到 0.5一份实战迁移指南
后端·rust
Source.Liu12 小时前
【学写LibreCAD】Win11下在MSYS2 UCRT64环境中搭建Qt+Rust混合开发环境(VSCode)完整笔记
c++·qt·rust
星释1 天前
Rust 练习册 111:构建锦标赛积分榜系统
开发语言·后端·rust
星释1 天前
Rust 练习册 116:杂志剪贴侦探游戏
开发语言·后端·rust
星释1 天前
Rust 练习册 113:构建你自己的 CSV 处理器
开发语言·windows·rust
wadesir1 天前
高效存储与访问:Rust语言三角矩阵压缩(从零开始掌握Rust稀疏矩阵存储技巧)
算法·矩阵·rust