当一个简单的“断言”就足够了时,为什么还要存在“assert_eq”和“assert_ne”?

Why do `assert_eq` and `assert_ne` exist when a simple `assert` will suffice?

assert!(a == b)assert_eq!(a, b) 占用更少的字符,而且在我看来,它更具可读性。

错误消息大致相同:

thread 'main' panicked at 'assertion failed: `(left == right)` (left: `1`, right: `2`)', src\main.rs:41

thread 'main' panicked at 'assertion failed: 1 == 2', src\main.rs:41

其实这个问题不仅仅是关于Rust的;我一直在单元测试框架中看到这些不同的断言宏或函数:

通常还有针对某些特定类型(如字符串或数组)的断言。有什么意义?

thread 'main' panicked at 'assertion failed: 1 == 2',

你的例子太简单了,看不出使用assert_eq!有很大的优势。考虑这段代码:

let s = "Hello".to_string();
assert!(&s == "Bye");

这是生成的恐慌消息:

'assertion failed: &s == "Bye"'    

现在让我们看看当我们使用 assert_eq!:

时会发生什么
let s = "Hello".to_string();
assert_eq!(&s, "Bye");

留言:

'assertion failed: `(left == right)` (left: `"Hello"`, right: `"Bye"`)'

此消息比前者提供了更多的见解。其他单元测试系统也经常这样做。