如何检查两个变量是否指向内存中的同一个对象? [英] How to check if two variables point to the same object in memory?

查看:38
本文介绍了如何检查两个变量是否指向内存中的同一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

struct Foo<'a> { bar: &'a str }

fn main() {
    let foo_instance = Foo { bar: "bar" };
    let some_vector: Vec<&Foo> = vec![&foo_instance];

    assert!(*some_vector[0] == foo_instance);
}

  1. 我想检查 foo_instance 是否引用与 *some_vector[0] 相同的实例,但我不能这样做......

  1. I want to check if foo_instance references the same instance as *some_vector[0], but I can't do this ...

我不想知道两个实例是否相等;我想检查变量是否指向内存中的同一个实例

I don't want to know if the two instances are equal; I want to check if the variables point to the same instance in the memory

能做到吗?

推荐答案

ptr::eq:

use std::ptr;

struct Foo<'a> {
    bar: &'a str,
}

fn main() {
    let foo_instance = Foo { bar: "bar" };
    let some_vector: Vec<&Foo> = vec![&foo_instance];

    assert!(ptr::eq(some_vector[0], &foo_instance));
}

在 Rust 1.17.0 中稳定之前,您可以执行转换为 *const T:

Before this was stabilized in Rust 1.17.0, you could perform a cast to *const T:

assert!(some_vector[0] as *const Foo == &foo_instance as *const Foo);

它将检查引用是否指向内存中的相同位置.

It will check if the references point to the same place in the memory.

这篇关于如何检查两个变量是否指向内存中的同一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆