本文簡要介紹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 eprintln用法及代碼示例
- Rust escape_default用法及代碼示例
- Rust empty用法及代碼示例
- Rust env用法及代碼示例
- Rust exit用法及代碼示例
- Rust eprint用法及代碼示例
- Rust UdpSocket.set_multicast_loop_v6用法及代碼示例
- Rust i64.overflowing_add_unsigned用法及代碼示例
- Rust Box.downcast用法及代碼示例
- Rust BTreeMap.last_key_value用法及代碼示例
- Rust str.make_ascii_uppercase用法及代碼示例
- Rust u128.checked_pow用法及代碼示例
- Rust usize.wrapping_mul用法及代碼示例
- Rust AtomicU8.fetch_sub用法及代碼示例
- Rust PanicInfo.payload用法及代碼示例
- Rust MaybeUninit.assume_init_mut用法及代碼示例
- Rust String.try_reserve用法及代碼示例
- Rust Mutex.new用法及代碼示例
- Rust f32.exp用法及代碼示例
- Rust Result.unwrap_or_else用法及代碼示例
- Rust slice.sort_unstable_by_key用法及代碼示例
- Rust Formatter.precision用法及代碼示例
- Rust i128.log2用法及代碼示例
- Rust OsStr.to_ascii_uppercase用法及代碼示例
- Rust f32.hypot用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Function std::ptr::eq。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。