我有一段代码,其中一个函数存在bug:
fn is_five(x: &i32) -> bool {
x == 5
}
fn main() {
assert!(is_five(&5));
assert!(!is_five(&6));
println!("Success!");
}
运行时出现错误:
error[E0277]: can't compare `&i32` with `{integer}`
--> main.rs:2:7
|
2 | x == 5
| ^^ no implementation for `&i32 == {integer}`
|
= help: the trait `std::cmp::PartialEq<{integer}>` is not implemented for `&i32`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
我通过比较两个值而不是一个地址和一个值的逻辑来解决了这个问题。
fn is_five(x: &i32) -> bool {
*x == 5
}
然而,我也随意尝试了借用方法,令我惊讶的是,它起作用了。
fn is_five(x: &i32) -> bool {
x == &5
}
我不理解两个地址是如何相同的?难道 ==
操作符有一些特性可以获取两端存储的值吗?