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

今天我们来看看一个类似的概念 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 radiusSquare(f64), // Variant Square takes a side length
}// Implement methods on the Shape enum
impl Shape {// Method to calculate the area of a shapefn 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 shapeslet circle = Shape::Circle(2.0);let square = Shape::Square(3.0);// Calculate and print the areas of different shapesprintln!("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.hqwc.cn/news/644562.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【iOS开发】(六)react Native 路由嵌套传参与框架原理(完)20240423

【iOS开发】(六)react Native 路由嵌套传参与框架原理&#xff08;完&#xff09;20240423 感谢拉钩教育的教学。 &#xff08;五&#xff09;我们介绍了四种路由导航&#xff0c;这一节我们介绍他们的嵌套传参和框架的整体原理。到这里&#xff0c;大家已经能用RN框架进行一些…

今心成长之路与人格频率学苑十年发展

在过去的十年里&#xff0c;今心老师以其非凡的人生经历和对人格频率学的深入探索&#xff0c;为无数人带来了巨大的鼓舞力量。他的成长之路充满坎坷与传奇&#xff0c;而人格频率学也在这十年间得到了长足的发展。      今心老师的少年时期颠沛流离&#xff0c;但他凭借坚…

【FMEA软件】FMEA,到底是给谁看的?

免费试用FMEA软件-免费版-SunFMEA FMEA&#xff0c;即故障模式与影响分析&#xff0c;是一种预防性的质量工具&#xff0c;广泛应用于各种行业&#xff0c;尤其是制造业和高科技领域。它的目的是在产品设计或过程设计阶段&#xff0c;通过系统地分析和识别潜在的故障模式&…

SAP Fiori开发中的JavaScript基础知识15 - 原型,object,constructor,class,继承

1. 前言 本文将介绍JavaScript中的核心概念 - 原型&#xff0c;并会介绍基于原型的应用场景object&#xff0c;constructor&#xff0c;class&#xff0c;继承。 本文会将这几个核心概念汇总在一篇博客中&#xff0c;因为这些概念是触类旁通的&#xff0c;希望对你有帮助。 …

MySQL数据库精讲001——概述

MySQL数据库精讲001——概述 文章目录 MySQL数据库精讲001——概述1.1 安装1.1.1 版本1.1.2 安装一、下载二、解压三、配置1. 添加环境变量2. 初始化MySQL3. 注册MySQL服务4. 启动MySQL服务5. 修改默认账户密码 四、登录MySQL五、卸载MySQL 1.1.3 连接1.1.4 企业使用方式(了解)…

解读DreamFusion:一个引人注目的AI生成内容领域的项目

什么是DreamFusion&#xff1f; DreamFusion使用2D扩散模型来实现文本到3D生成的任务。这项技术在ICLR 2023上获得了杰出论文奖&#xff0c;并成为了许多科研工作的基准。 简而言之&#xff0c;DreamFusion的目标是在没有3D数据监督的情况下&#xff0c;利用已有的2D生成模型根…

接口测试和Mock学习路线(中)

1.什么是 swagger Swagger 是一个用于生成、描述和调用 RESTful 接口的 WEB 服务。 通俗的来讲&#xff0c;Swagger 就是将项目中所有想要暴露的接口展现在页面上&#xff0c;并且可以进行接口调用和测试的服务。 现在大部分的项目都使用了 swagger&#xff0c;因为这样后端…

CentOS-7部署mysql、clickhouse并通过普罗米修斯、grafna监控告警

一、准备工作 1、系统环境 所用镜像&#xff1a;CentOS-7-x86_64-DVD-2009.iso 2、涉及安装包 3、克隆4台虚拟机 用途IP主机名Prometneus服务器192.168.15.129master被监控服务器1192.168.15.133node1mysql、clickhouse、grafana服务器192.168.15.134node2被监控服务器219…

LyricWikia, 一个让你玩物丧志的Python库

文章目录 LyricWikia: Python的歌词查找库背景LyricWikia是什么&#xff1f;安装简单的库函数使用方法场景示例搜索并显示歌词获取歌手的热门歌曲搜索并下载歌词 常见问题和解决方案总结 LyricWikia: Python的歌词查找库 背景 LyricWikia是一个用于查找和获取歌曲歌词的Python…

【Linux系统编程】第八弹---权限管理操作(中)

✨个人主页&#xff1a; 熬夜学编程的小林 &#x1f497;系列专栏&#xff1a; 【C语言详解】 【数据结构详解】【C详解】【Linux系统编程】 目录 1、修改文件权限的做法(二) 2、文件类型 3、可执行权限 4、创建文件/目录的默认权限 4.1、权限掩码 总结 前面一弹我们学…

MySQL基础之多表操作(多表查询,事务,索引)

目录 一、多表关系1.1 一对多1.2 外键约束1.3 一对一1.4 多对多 二、多表查询2.1 测试数据准备2.2 笛卡尔积2.3 内连接2.4 外连接2.5 子查询1.标量子查询2.列子查询3.行子查询4.表子查询 三、事务3.1 问题场景引入3.2 概念3.3 事务操作3.4 事务的四大特性ACID 四、索引4.1 概念…

干货|Python的交互式脚本式

Python交互式编程 我们可以在命令提示符中输入"Python"命令来启动Python解释器&#xff1a; $ python3执行以上命令后&#xff0c;出现如下窗口信息&#xff1a; $ python3 Python 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] on linux Type "help&…