我想测试两个类型为Rc<Trait>
的对象是否包含一个具体类型的相同实例,因此我将指针与Rc
中的对象进行比较,以确定是否相等.如果所有代码都驻留在同一个 crate 中,但当涉及多个 crate 时,它似乎工作正常.
在Rust 1.17中增加了功能Rc::ptr_eq
,从Rust 1.31开始,该功能与本问题中使用的手动指针比较具有相同的交叉 crate 问题.
这是 crate mcve
(src/lib.rs
)的实施:
use std::rc::Rc;
pub trait ObjectInterface {}
pub type Object = Rc<ObjectInterface>;
pub type IntObject = Rc<i32>;
impl ObjectInterface for i32 {}
/// Test if two Objects refer to the same instance
pub fn is_same(left: &Object, right: &Object) -> bool {
let a = left.as_ref() as *const _;
let b = right.as_ref() as *const _;
let r = a == b;
println!("comparing: {:p} == {:p} -> {}", a, b, r);
r
}
pub struct Engine {
pub intval: IntObject,
}
impl Engine {
pub fn new() -> Engine {
Engine {
intval: Rc::new(42),
}
}
pub fn run(&mut self) -> Object {
return self.intval.clone();
}
}
我使用以下代码(tests/testcases.rs
)测试实现:
extern crate mcve;
use mcve::{is_same, Engine, Object};
#[test]
fn compare() {
let mut engine = Engine::new();
let a: Object = engine.intval.clone();
let b = a.clone();
assert!(is_same(&a, &b));
let r = engine.run();
assert!(is_same(&r, &a));
}
在以下输出中运行测试结果:
comparing: 0x7fcc5720d070 == 0x7fcc5720d070 -> true
comparing: 0x7fcc5720d070 == 0x7fcc5720d070 -> false
thread 'compare' panicked at 'assertion failed: is_same(&r, &a)'
尽管指针似乎相同,但比较运算符==
如何可能返回false
?
以下是一些观察:
- 当两个对象(
a
和b
)生活在同一个 crate 中时,比较返回true
.然而,当在另一个 crate 中定义的功能Engine::run
返回其中一个对象(r
)时,比较返回false
. - 当我将测试函数放入
lib.rs
内时,测试正确通过. - 这个问题可以通过定义
struct Engine { intval: Object }
来解决,但我仍然对why感兴趣.