Rust : 关于Deref

一、原码

Deref Trait的原码如下:

css 复制代码
pub trait Deref: PointeeSized {
    type Target: ?Sized;
    fn deref(&self) -> &Self::Target;
}

impl<T: ?Sized> const Deref for &T {
    type Target = T;
    fn deref(&self) -> &T {
        *self
    }
}

二、关键词

隐式、自动解引用。

Deref Trait 是Rust的特色。它隐藏的很深,有时侯会感觉到很上头。

自动解引用,就是化繁为简的操作。

只有深刻理解这两者,才能真正理解Deref Trait的初衷。

三、常见的取引用和解引用操作

当 T实现了Deref Trait:

css 复制代码
*T = *(T.deref()) = <T as Deref>::Target

正常解引用;其中,T.deref() -> &< T as Deref >::Target。

css 复制代码
&*T  = &(*T):

先解引用得到< T as Deref>::Target,再取地址

css 复制代码
&**T = &(*(*T))

先进行第1次解引用,得到< T as Deref>::Target,再对< T as Deref>::Target进行解引用,得到<< T as Deref>::Target as Deref>::Target。再取地址。

css 复制代码
 *&T  = T

先取引用,后解引用。需要注意:这种操作可能报错,已经被move了。

css 复制代码
*&&T = &T; 

先两次取引用,后做一次解引用。

css 复制代码
&*T = T.deref();

四、点操作

以 T.method() 为例,其中点操作内含的自动解引用顺序如下:

step 1:

css 复制代码
T.method() 

如果T没有实现method(),则进行step 2

step 2:

css 复制代码
 (&*T).method()  = T.deref().method()

第2次解引用,如果没有成功,则进行step 3

step 3:

css 复制代码
(&**T).method() = T.deref().deref().method()

第3次解引用,如果没有成功,则进行step 3...

...

五、类型转换:&T ->&U

css 复制代码
T: Deref<Target=U> => &T =>&U

常见场景:函数的参数操作,如:

css 复制代码
 fn(&T)(){} ->fn(&U)(){} 
相关推荐
郝学胜-神的一滴8 小时前
Python 高级编程 019:类变量与实例变量彻底解析
开发语言·python·程序人生·软件构建
雪隐8 小时前
AI股票小助手07-TA-Lib 技术指标计算实战
人工智能·后端
掘金者阿豪8 小时前
一本书读懂微积分!
后端
Cosolar8 小时前
深入理解 LangChain Callback 机制:从入门到实战
人工智能·后端·面试
我登哥MVP8 小时前
Spring Boot 从“会用”到“精通”:SpringBoot MVC 请求处理全流程
java·spring boot·后端·spring·mvc·maven·intellij-idea
Thomas_YXQ8 小时前
Unity3D Addressable 深度优化热更性能消耗
开发语言·3d·unity·微信
aini_lovee8 小时前
C# 快递单打印系统(万能套打系统)
开发语言·c#
我登哥MVP8 小时前
Spring Boot 从“会用”到“精通”:ReturnValueHandler原理
java·spring boot·后端·spring·java-ee·maven·intellij-idea
天启HTTP8 小时前
开启全局代理后网络变慢,问题出在哪
开发语言·前端·网络·tcp/ip·php