Rust 如何检查两个引用变量是否借用同一对象?
我有一个所有存储只读引用的结构,例如:Rust 如何检查两个引用变量是否借用同一对象?,rust,borrowing,Rust,Borrowing,我有一个所有存储只读引用的结构,例如: struct Pt { x : f32, y : f32, } struct Tr<'a> { a : &'a Pt } 所以现在我有了 impl<'a> PartialEq for Tr<'a> { fn eq(&self, v : &Tr<'a>) -> bool { // self.a == v.a // doesn't work. } }
struct Pt { x : f32, y : f32, }
struct Tr<'a> { a : &'a Pt }
所以现在我有了
impl<'a> PartialEq for Tr<'a> {
fn eq(&self, v : &Tr<'a>) -> bool {
// self.a == v.a // doesn't work.
}
}
impl{
fn eq&self,v:&Tr将引用转换为原始指针并进行比较
impl<'a> PartialEq for Tr<'a> {
fn eq(&self, v: &Tr<'a>) -> bool {
self.a as *const _ == v.a as *const _
}
}
impl{
fn eq(&self,v:&Tr您可以用来比较两个指针的地址。引用(&T
或&mut T
)将自动强制底层指针(*const T
)当然,可变引用与另一个引用具有相同的地址是没有意义的,因为可变引用始终是独占引用,但它仍然可以强制为*常量T
// This derive will use the equality of the underlying fields
#[derive(PartialEq)]
struct Pt {
x: f32,
y: f32,
}
impl Pt {
fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
struct Tr<'a> {
a: &'a Pt,
}
impl<'a> Tr<'a> {
fn new(a: &'a Pt) -> Self {
Self { a }
}
}
// Here we use std::ptr::eq to compare the *addresses* of `self.a` and `other.a`
impl<'a> PartialEq for Tr<'a> {
fn eq(&self, other: &Tr<'a>) -> bool {
std::ptr::eq(self.a, other.a)
}
}
fn main() {
let tr_base1 = Pt::new(0.0, 0.0);
let tr_base2 = Pt::new(0.0, 0.0);
assert!(tr_base1 == tr_base2);
let tr1 = Tr::new(&tr_base1);
let tr2 = Tr::new(&tr_base2);
let tr3 = Tr::new(&tr_base1);
assert!(tr1 == tr3);
assert!(tr1.a == tr2.a);
assert!(tr1 != tr2);
}
//此派生将使用基础字段的相等性
#[衍生(部分)]
结构Pt{
x:f32,
y:f32,
}
impl Pt{
fn新(x:f32,y:f32)->自{
自{x,y}
}
}
结构Tr{
fn新(a:&'a Pt)->自{
自我{a}
}
}
//这里我们使用std::ptr::eq来比较'self.a'和'other.a'的*地址*`
恳求{
fn情商和自我,其他:&Tr
// This derive will use the equality of the underlying fields
#[derive(PartialEq)]
struct Pt {
x: f32,
y: f32,
}
impl Pt {
fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
struct Tr<'a> {
a: &'a Pt,
}
impl<'a> Tr<'a> {
fn new(a: &'a Pt) -> Self {
Self { a }
}
}
// Here we use std::ptr::eq to compare the *addresses* of `self.a` and `other.a`
impl<'a> PartialEq for Tr<'a> {
fn eq(&self, other: &Tr<'a>) -> bool {
std::ptr::eq(self.a, other.a)
}
}
fn main() {
let tr_base1 = Pt::new(0.0, 0.0);
let tr_base2 = Pt::new(0.0, 0.0);
assert!(tr_base1 == tr_base2);
let tr1 = Tr::new(&tr_base1);
let tr2 = Tr::new(&tr_base2);
let tr3 = Tr::new(&tr_base1);
assert!(tr1 == tr3);
assert!(tr1.a == tr2.a);
assert!(tr1 != tr2);
}