當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。