• rust的Defef和DerefMut学习


    rust的Defef

    介绍

    pub trait Deref {
       
        type Target: ?Sized;
    
        // Required method
        fn deref(&self) -> &Self::Target;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    用于不可变的解引用操作,例如 *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, 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,且 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: 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
  • 相关阅读:
    【MySQL功法】第4话 · 和kiko一起探索MySQL中的运算符
    maven升级版本后报错:Blocked mirror for repositories
    外包干了半年,快要废了。。。
    clean code-代码整洁之道 阅读笔记(第十二章)
    Python Flask Web开发二:数据库创建和使用
    Python实现猎人猎物优化算法(HPO)优化LightGBM回归模型(LGBMRegressor算法)项目实战
    AI电销机器人好不好用关键是什么?
    23.亨元模式
    SpringBoot整合SSMP
    管理需因人而异,因时而变
  • 原文地址:https://blog.csdn.net/wangkai6666/article/details/133841368