学习Rust的第10天:枚举和模式匹配

news2024/10/5 23:31:08

今天我们来看看一个类似的概念 enums 。

  • Enums: We saw that in Rust, enums are data types that list possible values, giving a simple and type-safe mechanism to describe alternatives. We looked at how to create enums and use them to represent similar possibilities, such as days of the week.
    枚举:我们看到在Rust中,枚举是列出可能值的数据类型,提供了一种简单且类型安全的机制来描述替代方案。我们研究了如何创建枚举并使用它们来表示类似的可能性,例如一周中的几天。
  • Methods in Enums: Similar to structs, we saw that we can implement methods on enums using an impl block. We demonstrated this by creating methods to calculate the area of different geometric shapes represented by an enum.
    枚举中的方法:与结构类似,我们看到可以使用 impl 块在枚举上实现方法。我们通过创建方法来计算枚举表示的不同几何形状的面积来证明这一点。
  • Option Enum: We discussed the Option enum, which is commonly used to handle scenarios where a value may be present or absent. We explored how Some represents a value being present, while None indicates the absence of a value. Additionally, we learned how to use the unwrap_or method to handle situations where we need to extract a value from an Option or provide a default value if it's absent.
    Option Enum:我们讨论了 Option enum,它通常用于处理值可能存在或不存在的情况。我们探讨了 Some 如何表示存在的值,而 None 表示不存在的值。此外,我们还学习了如何使用 unwrap_or 方法来处理需要从 Option 中提取值或提供默认值(如果没有)的情况。
  • Pattern Matching: Finally, we explored pattern matching using the match keyword, which allows us to check for multiple cases and execute specific code based on the matched pattern. We demonstrated how to use match to handle various cases and execute corresponding code blocks.
    模式匹配:最后,我们使用 match 关键字探索了模式匹配,它允许我们检查多个案例并基于匹配的模式执行特定代码。我们演示了如何使用 match 来处理各种情况并执行相应的代码块。

Introduction 介绍

Enums in Rust are data types that allow you to define a type by enumerating its possible values, providing a concise and type-safe way to represent alternatives.
Rust中的枚举是一种数据类型,允许您通过枚举其可能的值来定义类型,提供一种简洁且类型安全的方式来表示替代方案。

enum Day{
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday,
}

fn main(){
  let today = Day::Monday;
}

This is what enums basically are…
这就是 enums 基本上是...

If we had to store each day with the programming language we were going to study in Rust. We would do something like this with structs
如果我们不得不用Rust中将要学习的编程语言来存储每一天。我们会用 structs 做这样的事情

enum Day{
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday,
}

Struct TimeTable{
  day: Day,
  language: String,
}

fn main(){
  let day1 = TimeTable{
    day: Day::Monday,
    language: String::from("Rust"),
  };
}

An alternative way would be to store values inside enums .
另一种方法是将值存储在 enums 中。

enum Day{
  Monday(String),
  Tuesday(String),
  Wednesday(String),
  Thursday(String),
  Friday(String),
  Saturday(String),
  Sunday(String),
}

Struct TimeTable{
  day: Day,
  language: String,
}

fn main(){
  let day1 = Day::Monday(String::from("Rust"));
}

Methods in Enums 枚举中的方法

Just like we did for structs, we can create an impl block to implement methods in enums .
就像我们对 structs 所做的那样,我们可以创建一个 impl 块来实现 enums 中的方法。

// Define an enum called Shape to represent different geometric shapes
enum Shape {
    Circle(f64), // Variant Circle takes a radius
    Square(f64), // Variant Square takes a side length
}

// Implement methods on the Shape enum
impl Shape {
    // Method to calculate the area of a shape
    fn area(&self) -> f64 {
        match *self {
            Shape::Circle(radius) => 3.14 * radius * radius,
            Shape::Square(side_length) => side_length * side_length,
        }
    }
}

fn main() {
    // Create instances of different shapes
    let circle = Shape::Circle(2.0);
    let square = Shape::Square(3.0);

    // Calculate and print the areas of different shapes
    println!("Area of the circle: {:.2}", circle.area());
    println!("Area of the square: {:.2}", square.area());
}

Output: 输出量:

Area of the circle: 12.57
Area of the square: 9.00

Explanation 解释

  • We define an enum named Shape that represents geometric shapes.
    我们定义了一个名为Shape的枚举来表示几何形状。
  • Shape has two variations: Circle(f64), which represents a circle with a radius, and Square(f64), which represents a square with a side length.
    形状有两种变体:圆形(f64),表示具有半径的圆形;方形(f64),表示具有边长的方形。
  • The Shape enum is implemented with a method called area().
    Shape 枚举是用一个名为 area() 的方法实现的。
  • The area() method takes a reference to self (the enum instance) and returns a f64 representing the area of the shape.
    area() 方法引用 self (枚举实例)并返回表示形状区域的 f64 。
  • The match keyword in Rust allows for pattern matching against different values and executing code based on the matched pattern, providing a concise and powerful way to handle various cases or variants within enums, structs, or other types.
    Rust中的 match 关键字允许对不同的值进行模式匹配,并基于匹配的模式执行代码,提供了一种简洁而强大的方式来处理枚举,结构或其他类型中的各种情况或变体。
  • For Shape::Circle, it calculates the area using the formula π * radius^2.
    对于 Shape::Circle ,它使用公式π * 半径^2计算面积。
  • For Shape::Square, it calculates the area using the formula side_length^2.
    对于 Shape::Square ,它使用公式side_length^2计算面积。
  • In the main() function: 在 main() 函数中:
  • Instances of different shapes (circle and square) are created.
    将创建不同形状的图形( circle 和 square )。
  • The area() method is called on each shape instance to calculate and print their respective areas.
    在每个形状实例上调用 area() 方法来计算和打印它们各自的面积。
  • Finally, the areas of the circle and square are printed with two decimal places using println!() statements.
    最后,使用 println!() 语句将圆形和正方形的面积打印为两位小数。

Option Enum Option枚举

The Option enum in Rust represents the presence or absence of a value, providing a concise and type-safe way to handle scenarios where a value may be present or missing.
Rust中的 Option enum 表示值的存在或不存在,提供了一种简洁和类型安全的方式来处理值可能存在或缺失的场景。

If we have a value that’s null, or can potentially not exist we use a null value but Rust does not have a null type, We can use Option enums for these situations.
如果我们有一个null值,或者可能不存在,我们使用 null 值,但Rust没有null类型,我们可以使用Option枚举来处理这些情况。

This enforces the type system that we have to handle the null case leading to a safer code.
这强制了类型系统,我们必须处理null情况,从而导致更安全的代码。

  • Some is used when a value is present
    Some 在存在值时使用
  • none is used when when a value is absent
    none 在缺少值时使用
  • From here we can use match operations to enumerate cases for both.
    从这里我们可以使用 match 操作来枚举两者的情况。
fn get_first_element(numbers: &[i32]) -> Option<i32> {
    if let Some(&first) = numbers.first() {
        Some(first) // Return the first element wrapped in Some if it exists
    } else {
        None // Return None if the slice is empty
    }
}

Explanation 解释

  • The get_first_element function takes a slice of integers numbers as its parameter.
    get_first_element 函数接受一个整数切片 numbers 作为其参数。
  • It uses the .first() method on the slice to retrieve an Option containing a reference to the first element of the slice.
    它使用切片上的 .first() 方法来检索包含对切片第一个元素的引用的Option。
  • If the slice is not empty, .first() returns Some(&first), where first is a reference to the first element.
    如果切片不为空,则 .first() 返回 Some(&first) ,其中 first 是对第一个元素的引用。

The function pattern matches on the Option:
函数模式在Option上匹配:

  • If the Option is Some, it extracts the value of first and wraps it in another Some, effectively unwrapping the reference.
    如果Option是 Some ,它提取 first 的值并将其包装在另一个 Some 中,有效地展开引用。
  • If the Option is None, indicating an empty slice, it returns None.
    如果Option是 None ,表示一个空切片,则返回 None 。

Using Option enums with primitive data types
将Option枚举与基元数据类型一起使用

fn main(){
  let x: i8 = 10;
  let y: Option<i8> = Some(14);
  
  let sum = x + y;
}

This code will result in an error, because we cannot add i8 to Option<i8> because they are different data types.
这段代码将导致错误,因为我们不能将 i8 添加到 Option<i8> ,因为它们是不同的数据类型。

To complete this operation we can use the unwrap_or() method.
要完成此操作,我们可以使用 unwrap_or() 方法。

unwrap_or(data) returns the value of the Option enum if it exits, if it does not exist it returns data.
unwrap_or(data) 如果存在,则返回 Option enum 的值,如果不存在,则返回 data 。

fn main(){
  let x: i8 = 10;
  let y: Option<i8> = Some(14);
  let sum = x + y.unwrap_or(0);
  println!("{}",sum);
}

Output: 输出量:

24

Pattern matching 模式匹配

We have used match in the guessing game, It is used to check for multiple cases and run a specific block of code for each value.
我们在猜谜游戏中使用了 match ,它用于检查多个情况并为每个值运行特定的代码块。

Here is a simple example:
下面是一个简单的例子:

fn main() {
    let number = 5;

    match number {
        1 => println!("It's one!"),
        2 => println!("It's two!"),
        3 | 4 => println!("It's three or four!"),
        8 => {
          println!("This is a multi-line function in a match expression");
        },
        _ => println!("It's something else!"),
    }
}
  • The match keyword is used to perform pattern matching on the value of number.
    match 关键字用于对 number 的值执行模式匹配。
  • Each pattern in the match expression is followed by =>, indicating the code to execute if the pattern matches.
    match 表达式中的每个模式后面都跟有 => ,表示如果模式匹配则执行的代码。
  • If number matches the pattern 1, the message "It's one!" is printed.
    如果 number 匹配模式 1 ,则消息“It's one!”是印刷的。
  • If number matches the pattern 2, the message "It's two!" is printed.
    如果 number 匹配模式 2 ,则消息“It's two!”是印刷的。
  • If number matches the patterns 3 or 4, the message "It's three or four!" is printed.
    如果 number 匹配模式 3 或 4 ,则消息“是三或四!”是印刷的。
  • If number matches the pattern 8, the code inside the curly braces is executed, printing "This is a multi-line function in a match expression".
    如果 number 匹配模式 8 ,则执行花括号内的代码,打印“This is a multi-line function in a match expression”。
  • The _ pattern acts as a wildcard and matches any value not explicitly listed. If number doesn't match any of the specified patterns, the message "It's something else!" is printed.
    _ 模式作为一个前缀,匹配任何没有显式列出的值。如果 number 不匹配任何指定的模式,则消息“It's something else!”是印刷的。
  • In this specific example, since number is 5, it doesn't match any of the specific patterns, so the wildcard pattern _ is used, and the message "It's something else!" is printed.
    在这个特定的例子中,由于 number 是 5 ,它不匹配任何特定的模式,所以使用了重复模式 _ ,并且消息“It's something else!”是印刷的。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1619336.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MT8788智能模块简介_MTK联发科安卓核心板方案厂商

MT8788安卓核心板是一款具备超高性能和低功耗的4G全网通安卓智能模块。该模块采用联发科AIOT芯片平台&#xff0c;供货周期长。 MT8788核心板搭载了12nm制程的四个Cortex-A73处理器核心和四个Cortex-A53处理器核心&#xff0c;最高主频可达2.0GHz。板载内存容量可选为4GB64GB(也…

【Win】怎么下载m3u8视频\怎么通过F12开发人员工具获取视频地址\怎么下载完整的.ts格式视频

怎么下载m3u8视频&#xff1f;首先通过浏览器本地的开发人员工具&#xff0c;获取m3u8的地址&#xff0c;然后再通过第三方下载工具下载&#xff0c;此处以N_m3u8DL-CLI_v3.0.2为例 如下图的步骤&#xff0c;即可获取到视频的m3u8地址 打开N_m3u8DL-CLI_v3.0.2&#xff0c;粘贴…

生成式AI在B端产品的应用分析

AI产品发展到现在&#xff0c;消费端的产品应用还受到比较大的限制&#xff1b;但是在B端&#xff0c;已经有了不错的表现。作者总结了AI产品在B端的几款应用&#xff0c;一起来看看表现如何。 生成式AI在B端产品的应用分析© 由 ZAKER 提供 随着今年生成式AI应用的大范围…

ROS1快速入门学习笔记 - 04创建工作环境与功能包

一、定义 工作空间(workspace)是一个存放工程开发相关文件的文件夹。 src:代码空间&#xff08;Source Space&#xff09;build: 编辑空间&#xff08;Build Space&#xff09;devel:开发空间&#xff08;Development Space&#xff09;install:安装空间&#xff08;Install …

【网络安全】HTTP协议 — 基础

专栏文章索引&#xff1a;网络安全 有问题可私聊&#xff1a;QQ&#xff1a;3375119339 目录 学习目标​ 一、万维网的诞生与发展​编辑 1.万维网的诞生与发展 2.HTTP协议诞生与发展 二、网络基础 1.TCP/IP分层传输 1&#xff09;TCP/IP协议 2&#xff09;封装与拆封 …

【linux】匿名管道|进程池

1.进程为什么要通信&#xff1f; 进程也是需要某种协同的&#xff0c;所以如何协同的前提条件(通信) 通信数据的类别&#xff1a; 1.通知就绪的 2.单纯的数据 3.控制相关的信息 2.进程如何通信&#xff1f; 进程间通信&#xff0c;成本会高一点 进程间通信的前提&#xff0c;先…

vue【vuex状态管理】

1&#xff1a;vuex是什么&#xff1a; vuex是一个状态管理工具&#xff0c;状态就是指的数据&#xff0c;可以将数据存放到vuex中以供其他组件使用时进行调用 2&#xff1a;应用场景&#xff1a; ①&#xff1a;像用户登录客户端&#xff0c;这个用户的数据需要在多个组件中…

VUE3 ref,props,生命周期

1.--ref属性 1.1代码 1.1.1子表 <template><div class"person"><h1>中国</h1><h2 ref"title2">北京</h2><h3>尚硅谷</h3><button click"showLog">点我输出h2这个元素</button>&l…

每天五分钟计算机视觉:基于YOLO算法精确分类定位图片中的对象

滑动窗口的卷积的问题 滑动窗口的卷积实现效率很高,但是它依然不能够输出最精准的边界框,比如下面所示: 我们可以看到蓝色框不论在什么位置都不能很好的确定车的位置,有一个算法是YOLO 算法它能够帮助我们解决这个问题。 YOLO 算法 比如我们的输入图像是100*100,我们会…

【网络安全】对称加密、非对称加密以及密钥分配

目录 1、对称加密 2、非对称加密 3、如何分配对称密钥&#xff1f; 4、如何分配非对称密钥&#xff1f; 1、对称加密 所谓对称加密&#xff0c;就是指加密密钥与解密密钥都使用相同的密钥。如下图所示&#xff0c;通信双方使用的就是对称加密密钥。//代表&#xff1a;DES和…

Hive服务详解

Hive服务 HiveServer2、Hive Metastore 服务服务共同构成了 Hive 生态系统中的核心功能&#xff0c;分别负责管理元数据和提供数据查询服务&#xff0c;为用户提供了一个方便、高效的方式来访问和操作存储在 Hive 中的数据。 1. Hive 查询服务&#xff08;HiveServer2&#xf…

恶补《操作系统》2_1——王道学习笔记

2操作系统-进程 2.1_1 进程的定义、组成、组织方式、特征 组成&#xff1a;PCB&#xff08;进程存在唯一的标志&#xff09;&#xff0c;程序段&#xff0c;数据段 组织方式&#xff1a;链接方式&#xff0c;指针指向不同的队列&#xff1b;索引方式&#xff0c;索引表 特征…

【深度学习】yolo-World,数据标注,zeroshot,目标检测

仓库&#xff1a;https://github.com/AILab-CVC/YOLO-World 下载权重&#xff1a; 仓库下载和环境设置 下载仓库&#xff1a;使用以下命令从 GitHub 上克隆仓库&#xff1a; git clone --recursive https://github.com/AILab-CVC/YOLO-World.git创建并激活环境&#xff1a…

VMmark 4 - 虚拟化平台基准测试

VMmark 4 - 虚拟化平台基准测试 VMmark is a free tool used to measure the performance and scalability of virtualization platforms. 请访问原文链接&#xff1a;VMmark 4 - 虚拟化平台基准测试&#xff0c;查看最新版。原创作品&#xff0c;转载请保留出处。 作者主页…

GPT与GAN结合生成图像——VQGAN原理解析

1、前言 这篇文章&#xff0c;我们讲VQ_GAN&#xff0c;这是一个将特征向量离散化的模型&#xff0c;其效果相当不错&#xff0c;搭配Transformer&#xff08;GPT&#xff09;或者CLIP使用&#xff0c;达到的效果在当时可谓是令人拍案叫绝&#xff01; 原论文&#xff1a;Tam…

栈和队列-介绍与实现(超级!!!详解-C语言)

目录 栈 栈的介绍 栈的概念 栈的结构 栈的实现 初始化栈 StackInit 销毁栈 StackDestroy 入栈 StackPush 出栈 StackPop 获取栈顶元素 StackTop 检查栈是否为空 StackEmpty 获取栈中有效元素个数 StackSize 队列 队列的介绍 队列的概念 队列的结构 队列的应用 队列的实现 …

LabVIEW与Modbus协议的多点温度监控系统

LabVIEW与Modbus协议的多点温度监控系统 随着工业自动化和智能化水平的不断提升&#xff0c;对于现场监控技术的需求日益增长。开发了一种基于LabVIEW与Modbus协议的多点温度监控系统&#xff0c;实现高效、准确的温度数据采集、处理和显示&#xff0c;以及数据存储功能&#…

【IR 论文】Google 对通过 prompt LLM 做 Query Expansion 的工作

论文&#xff1a;Query Expansion by Prompting Large Language Models ⭐⭐⭐ Google Research, arxiv:2305.03653 论文速读 之前我在论文笔记 Query2doc 中介绍了信息检索&#xff08;IR&#xff09;以及 Query Expansion 的相关背景知识。 本篇文章是 Google 发表的关于对…

Maven:配置与使用指南1

https://mvnrepository.com Maven 1.maven简介 不同模块的jar包以及同时设计的功能的微小变化版本&#xff1b; 真实的开发环境&#xff1a;我们将我们的源代码在服务器上重新编译重新打包&#xff0c;工程升级维护过程繁琐 1.Maven是一个项目管理工具&#xff0c;将项目开…

SpringBoot xxl-job 任务调度

首先官网下载xxl-job的源代码&#xff0c;然后切换到jdk8&#xff0c;等Maven下载依赖 执行mysql的脚本&#xff0c;修改连接配置&#xff0c;启动admin站点 默认地址 http://localhost:8080/xxl-job-admin/ 先新增一个任务执行器&#xff0c;指向未来任务代码的站点 然后在…