[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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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