当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust eq用法及代码示例


本文简要介绍rust语言中 Function std::ptr::eq 的用法。

用法

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

比较原始指针是否相等。

这与使用 == 运算符相同,但不那么通用:参数必须是 *const T 原始指针,而不是任何实现 PartialEq 的东西。

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

例子

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));

切片也通过它们的长度(胖指针)进行比较:

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]));

特征也通过它们的实现进行比较:

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

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

let wrapper = Wrapper { member: 10 };

// Pointers have equal addresses.
assert!(std::ptr::eq(
    &wrapper as *const Wrapper as *const u8,
    &wrapper.member as *const i32 as *const u8
));

// Objects have equal addresses, but `Trait` has different implementations.
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,
));

// Converting the reference to a `*const u8` compares by address.
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,
));

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Function std::ptr::eq。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。