Rust系列(四) trait备忘录(持续更新)

上一篇:Rust系列(三) 类型系统与trait

基于官方文档进行简单学习记录,保证所有示例是可运行的基本单元。测试rust程序除了使用官方的playground之外,还可以通过定义[[example]]来运行程序。

文章目录

  • [1. Deref](#1. Deref)
  • [2. DerefMut](#2. DerefMut)

1. Deref

用于不可变对象的解引用操作,语法类似*v
官方文档: https://doc.rust-lang.org/std/ops/trait.Deref.html
trait源码

rust 复制代码
pub trait Deref {
    type Target: ?Sized;

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

备注: DerefDerefMut 设计之初就是为了适配和简化智能指针而设计的,应该避免为非智能指针实现相关trait,以造成混淆。
Deref coercion

假设类型T实现了Deref<Target = U> trait,有一个类型为T的变量x,有下面几条规则成立:

  • *x等价于*Deref::deref(&x)
  • 类型T必须实现所有类型U的不可变方法

应用示例

rust 复制代码
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::<char> = DerefExample { value: 'a' };
    let target: char = *x;
    // a a
    println!("{} {}", target, 'a');
}

2. DerefMut

用于可变对象的解引用操作,语法类似*v = 1
官方文档: https://doc.rust-lang.org/std/ops/trait.DerefMut.html
trait源码

rust 复制代码
pub trait DerefMut: Deref {
    // Required method
    fn deref_mut(&mut self) -> &mut Self::Target;
}

DerefMut coercion

假设类型T实现了DerefMut<Target = U> trait,有一个类型为T的变量x,有下面几条规则成立:

  • *x等价于*DerefMut::deref_mut(&mut x)
  • 类型T必须实现所有类型U的可变和不可变方法

应用示例

rust 复制代码
use std::ops::{Deref, DerefMut};

struct DerefMutExample<T> {
    value: T,
}

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

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

impl<T> DerefMut for DerefMutExample<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}

fn main() {
    let mut x: DerefMutExample::<char> = DerefMutExample { value: 'a' };
    // a a
    println!("{} {}", *x, 'a');
    *x = 'b';
    // b a
    println!("{} {}", *x, 'a');
}
相关推荐
Predestination王瀞潞9 小时前
安装了Anaconda在系统终端却无法使用python命令
linux·开发语言·python
艾莉丝努力练剑11 小时前
【C++:异常】C++ 异常处理完全指南:从理论到实践,深入理解栈展开与最佳实践
java·开发语言·c++·安全·c++11
岁忧17 小时前
GoLang五种字符串拼接方式详解
开发语言·爬虫·golang
tyatyatya17 小时前
MATLAB基础数据类型教程:数值型/字符型/逻辑型/结构体/元胞数组全解析
开发语言·matlab
i***132418 小时前
Spring BOOT 启动参数
java·spring boot·后端
IT_Octopus18 小时前
(旧)Spring Securit 实现JWT token认证(多平台登录&部分鉴权)
java·后端·spring
kk哥889918 小时前
Spring详解
java·后端·spring
S***267518 小时前
Spring Cloud Gateway 整合Spring Security
java·后端·spring
码事漫谈18 小时前
C++单元测试框架选型与实战速查手册
后端
OneLIMS18 小时前
Windows Server 2022 + IIS + ASP.NET Core 完整可上传大文件的 报错的问题
windows·后端·asp.net