rust的Defef和DerefMut学习

rust的Defef

介绍

pub trait Deref {
   
    type Target: ?Sized;

    // Required method
    fn deref(&self) -> &Self::Target;
}

用于不可变的解引用操作,例如 *v ( immutable dereferencing operations)。

除了在不可变上下文中使用(一元)* 运算符进行显式解引用操作(for explicit dereferencing operations with the (unary) * operator in immutable contexts)之外,Deref 还在许多情况下由编译器隐式使用。这种机制称为“Deref 强制 Deref coercion”;在可变上下文中,请使用 DerefMut。

为智能指针实现 Deref 可以方便地访问其背后的数据(makes accessing the data behind them convenient),这就是他们实现 Deref 的原因。另一方面,关于 Deref 和 DerefMut 的规则是专门为适应智能指针而设计的(were designed specifically)。因此,Deref 应该仅针对智能指针实现,以避免混淆。

出于类似的原因,这个特性永远不应该失败。当隐式调用 Deref (invoked implicitly)时,解引用期间(Failure during dereferencing)的失败可能会非常令人困惑。

关于 Deref coercion 更多信息

If T implements Deref<Target = U>, and x is a value of type T, then:

  • In immutable contexts, *x (where T is neither a reference nor a raw pointer) is equivalent to *Deref::deref(&x).
  • Values of type &T are coerced to values of type &U
  • T implicitly implements all the (immutable) methods of the type U.
  • 如果 T 实现 Deref<Target = U>,且 x 是类型为 T 的值,那immutable场景下,*x(T既不是一个引用,也不是一个原始指针),等价于 *Deref::deref(&x)
    (Deref::deref(&x) 返回值是 &Self::U,然后解引用是 Self::U)
  • &T 类型的值被强制转换为 &U 类型的值(应该说的是deref方法)
  • T 隐式实现 U 类型的所有(不可变)方法 (有待理解)

示例1

use std::ops::Deref;

struct DerefExample<T> {
   
    value: T
}

impl<T> Deref for DerefExample<T> {
   
    type Target = T;

    fn deref(&self) -> &Self::Target {
   
        &self.value
    }
}

fn main() {
   
    let x = DerefExample {
    value: 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值