如何比较两个指针?

玻璃翼

我想在此循环中比较两个指针:

#[derive(Debug)]
struct Test {
    first: i32,
    second: i32
}

fn main() {
    let test = vec![Test {first: 1, second: 2}, Test {first: 3, second: 4}, Test {first: 5, second: 6}];

    for item in test.iter() {
        println!("---                  {:?}", item);
        println!("item                 {:p}", item);
        println!("test.last().unwrap() {:p}", test.last().unwrap());

        //  if item == test.last().unwrap() {
        //      println!("Last item!");
        //  }
    }
}

println给我相同的地址:

---                  Test { first: 1, second: 2 }
item                 0x563caaf3bb40
test.last().unwrap() 0x563caaf3bb50
---                  Test { first: 3, second: 4 }
item                 0x563caaf3bb48
test.last().unwrap() 0x563caaf3bb50
---                  Test { first: 5, second: 6 }
item                 0x563caaf3bb50
test.last().unwrap() 0x563caaf3bb50

但是,当我取消注释该if语句时,将引发以下错误:

error[E0369]: binary operation `==` cannot be applied to type `&Test`
  --> src/main.rs:20:17
   |
20 |         if item == test.last().unwrap() {
   |            ---- ^^ -------------------- &Test
   |            |
   |            &Test
   |
   = note: an implementation of `std::cmp::PartialEq` might be missing for `&Test`

如何只比较两个指针?

罗德里戈

当您比较指针时,您实际上是在比较那些指针所指向的值。这是因为类型中有很多实现std

impl<'_, '_, A, B> PartialEq<&'_ B> for &'_ A
where
    A: PartialEq<B> + ?Sized,
    B: ?Sized,

正是这样做的。

如果要比较指针本身,可以使用std::ptr::eq

pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool

请注意,即使使用原始指针,它也是安全的,因为它不会取消引用指针。由于从引用到原始指针具有自动强制,因此可以使用:

if std::ptr::eq(item, test.last().unwrap()) {
    println!("Last item!");
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章