Function std::ptr::eq1.17.0[][src]

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

比较裸指针是否相等。

这与使用 == 运算符相同,但泛型较少: 参数必须是 *const T 裸指针,而不是任何实现 PartialEq 的东西。

这可用于按地址比较 &T 引用 (隐式强制为 *const T),而不是比较它们指向的值 (PartialEq for &T 实现的作用)。

Examples

use std::ptr;

let five = 5;
let other_five = 5;
let five_ref = &five;
let same_five_ref = &five;
let other_five_ref = &other_five;

assert!(five_ref == same_five_ref);
assert!(ptr::eq(five_ref, same_five_ref));

assert!(five_ref == other_five_ref);
assert!(!ptr::eq(five_ref, other_five_ref));
Run

切片还通过其长度 (胖指针) 进行比较:

let a = [1, 2, 3];
assert!(std::ptr::eq(&a[..3], &a[..3]));
assert!(!std::ptr::eq(&a[..2], &a[..3]));
assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
Run

Traits 的实现方式也进行了比较:

#[repr(transparent)]
struct Wrapper { member: i32 }

trait Trait {}
impl Trait for Wrapper {}
impl Trait for i32 {}

let wrapper = Wrapper { member: 10 };

// 指针具有相等的地址。
assert!(std::ptr::eq(
    &wrapper as *const Wrapper as *const u8,
    &wrapper.member as *const i32 as *const u8
));

// 对象具有相等的地址,但是 `Trait` 具有不同的实现。
assert!(!std::ptr::eq(
    &wrapper as &dyn Trait,
    &wrapper.member as &dyn Trait,
));
assert!(!std::ptr::eq(
    &wrapper as &dyn Trait as *const dyn Trait,
    &wrapper.member as &dyn Trait as *const dyn Trait,
));

// 将引用转换为 `*const u8` 时,将按地址进行比较。
assert!(std::ptr::eq(
    &wrapper as &dyn Trait as *const dyn Trait as *const u8,
    &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
));
Run