在创建存储DST的结构(例如,原始切片)时,我可以使用常规#[derive(Eq, PartialEq, Ord, PartialOrd)]工具在我的类型上获得此特征的实现:
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct A([u8]);
Run Code Online (Sandbox Code Playgroud)
但是,如果我手动实现它们,那么编译器会抱怨我的类型没有实现Sized:
struct A([u8]);
impl AsRef<[u8]> for A {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl<S: AsRef<[u8]>> PartialEq<S> for A {
fn eq(&self, other: &S) -> bool {
self.0.eq(other.as_ref())
}
}
impl Eq for A { }
impl<S: AsRef<[u8]>> PartialOrd<S> for A {
fn partial_cmp(&self, other: &S) -> Option<Ordering> {
let slice: &[u8] = &self.0;
slice.partial_cmp(other.as_ref())
}
}
impl Ord for A {
fn cmp(&self, …Run Code Online (Sandbox Code Playgroud) 当在Rust中将指向函数的原始指针存储在Rust中时,程序的行为可能会根据原始指针的可变性以意想不到的方式改变。
使用const指针可以得到预期的结果。
也可以在操场上查看以下代码:
type ExternFn = unsafe extern "C" fn() -> ();
unsafe extern "C" fn test_fn() {
println!("Hello!");
}
mod mut_ptr {
use super::{ExternFn, test_fn};
#[derive(Debug, Eq, PartialEq)]
pub struct FunctionHolder {
function: *mut ExternFn,
}
impl FunctionHolder {
pub fn new() -> Self {
FunctionHolder {
function: (&mut (test_fn as ExternFn) as *mut _),
}
}
pub fn call(&self) {
if !self.function.is_null() {
unsafe { (&*self.function)(); }
}
}
}
}
mod const_ptr { …Run Code Online (Sandbox Code Playgroud)