[Rust] PartialEq in test

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

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

impl PositiveNonzeroInteger {
    fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
        // Hmm... Why is this always returning an Ok value?
        if value == 0 {
            Err(CreationError::Zero)
        } else if (value < 0) {
            Err(CreationError::Negative)
        } else {
            Ok(PositiveNonzeroInteger(value as u64))
        }
    }
}

#[test]
fn test_creation() {
    assert!(PositiveNonzeroInteger::new(10).is_ok());
    assert_eq!(
        Err(CreationError::Negative),
        PositiveNonzeroInteger::new(-10)
    );
    assert_eq!(Err(CreationError::Zero), PositiveNonzeroInteger::new(0));
}

The PartialEq trait in Rust is used to enable equality comparisons (== and !=) on types. In the code snippet you've shared, PartialEq is derived for both the CreationError enum and the PositiveNonzeroInteger struct to allow for these equality comparisons, which are particularly useful and necessary in the context of testing.

Deriving PartialEq for CreationError and PositiveNonzeroInteger is necessary for enabling equality comparisons in tests, which is a common practice to check if the code behaves as expected, especially when dealing with error handling and custom types in Rust.

posted @   Zhentiw  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-03-01 [Typescript] Clean type
2020-03-01 [Debug] debug module
2020-03-01 [CLI] Create a Hybrid Single-Multi Command Node.js CLI with Oclif and TypeScript
2020-03-01 [CLI] Convert a Single Command CLI into a Multi Command CLI with Oclif and TypeScript
2020-03-01 [CLI] Create a Single-Command Node.js CLI with Oclif, TypeScript and Yarn Workspaces
2020-03-01 [Custom CLI] Develop and Publish a Node.js CLI from Scratch
2019-03-01 [Compose] 21. Apply Natural Transformations in everyday work
点击右上角即可分享
微信分享提示