学习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 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.mfbz.cn/a/569030.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Dropout Feature Ranking for Deep Learning Models

摘要 深度神经网络( deep neural networks&#xff0c;DNNs )在多个领域取得了最新的研究成果。不幸的是&#xff0c;DNNs因其不可解释性而臭名昭著&#xff0c;从而限制了其在生物和医疗保健等假说驱动领域的适用性。此外&#xff0c;在资源受限的环境下&#xff0c;设计依赖…

沐风老师3dMax万有引力插件ToGround使用方法详解

3dMax万有引力插件ToGround使用教程 3dMax万有引力插件ToGround&#xff0c;用于在复杂地形&#xff08;曲面&#xff09;上将对象放置在适当高度的实用工具。例如&#xff1a;将大量的人、植物和汽车快速放置在一个街道、公园和小跑道高度不同的区域尤其有用。 【适用版本】 …

android openGL ES详解

1、渲染线程与主线程的通信 两个线程之间的通信可以用如下方法: 在主线程中的 GLSurfaceView 实例可以调用 queueEvent( &#xff09;方法传递一个 Runnable 给后台渲染线程&#xff0c;渲染线程可以调用 Activity 的 runOnUIThread()来传递事件 (event) 给主线程。 2、顶点…

SQLite FTS3 和 FTS4 扩展(三十二)

返回&#xff1a;SQLite—系列文章目录 上一篇&#xff1a;SQLite 的命令行 Shell(三十一&#xff09; 下一篇&#xff1a;SQLite—系列文章目录 概述 FTS3 和 FTS4 是 SQLite 虚拟表模块&#xff0c;允许用户执行 对一组文档进行全文搜索。最常见&#xff08;和最有效…

Linux之yum和vim的使用

一、yum的使用 yum 后面跟install要安装的文件名&#xff1a; 若你要安装的文件已经存在&#xff0c;则会出现&#xff1a; 要删除文件&#xff1a; yum remore文件名即可删除 在我们安装完lrzsz之后&#xff0c;可以用rz指令和sz指令&#xff1a; rz指令可以从window窗口中…

开源模型应用落地-chatglm3-6b-集成langchain(十)

一、前言 langchain框架调用本地模型&#xff0c;使得用户可以直接提出问题或发送指令&#xff0c;而无需担心具体的步骤或流程。通过LangChain和chatglm3-6b模型的整合&#xff0c;可以更好地处理对话&#xff0c;提供更智能、更准确的响应&#xff0c;从而提高对话系统的性能…

LoggerFactory is not a Logback

错误信息 LoggerFactory is not a Logback LoggerContext but Logback is on the classpath. Either remove Logback or the competing implementation (class org.slf4j.impl.SimpleLoggerFactory loaded from file:/D:/maven/repository/org/slf4j/slf4j-simple/1.7.26/slf…

easyx库的学习(鼠标信息)

前言 本次博客是作为介绍easyx库的使用&#xff0c;最好是直接代码打到底&#xff0c;然后看效果即可 代码 int main() {initgraph(640, 480, EX_SHOWCONSOLE|EX_DBLCLKS);setbkcolor(RGB(231, 114, 227));cleardevice();//定义消息结构体ExMessage msg { 0 };//获取消息wh…

SpringBoot+Vue开发记录(三)

说明&#xff1a;本篇文章的主要内容为需求分析。需求分析这一部分很重要&#xff0c;也稍微有点子难搞&#xff0c;所以本篇文章里的有些内容会有失偏颇。 一、准备步骤 我打算做一个刷题项目&#xff0c;但是具体这个项目该怎么做&#xff0c;我是一头雾水。 所以就要先进行…

OPTEE的FTRACE跟踪技术实战

【按语】:对于排除性能问题或优化代码来说,有没有更好的工具可以使用?FTRACE记录了对函数的所有调用,并包含计时信息。因此,对于排除性能问题或优化代码来说,它是一个很有价值的工具。本博客描述如何使用FTRACE为TA生成函数调用图。相关知识点介绍,请参考OPTEE Ftrace函…

k8s calico vxlan式详解

之前的文章讲了k8s ipip模式的使用以及流量路径&#xff0c;本篇文章主要是来讲解一下vxlan 模式下pod 流量是如何通信的。 一、ipip模式转vxlan 修改calico backend参数 将calico_backend参数由bird设置为vxlan,因为vxlan部署不使用bgp 修改calico controllers的configmap…

第100+6步 ChatGPT文献复现:ARIMAX预测新冠

基于WIN10的64位系统演示 一、写在前面 我们继续来解读ARIMAX模型文章&#xff0c;这一轮带来的是&#xff1a; 《PLoS One》杂志的2022年一篇题目为《A data-driven eXtreme gradient boosting machine learning model to predict COVID-19 transmission with meteorologic…

树莓派驱动开发----iic驱动oled屏幕篇

水一期吧&#xff0c;上效果 有点模糊&#xff0c;我直接说吧&#xff0c;修改设备树&#xff0c;iic1&#xff0c;地址0x3c&#xff0c;然后编写驱动文件&#xff0c;app文件&#xff0c;挂载驱动模块后在终端输入 /*******************************************************…

Appium一本通

Appium介绍 概念&#xff1a;Appium是一个移动App(手机应用)自动化工具。 用途&#xff1a;重复性任务、爬虫、自动化测试。 特点&#xff1a;开源免费、多平台支持(ios\android)、多类型支持(native\webview)、类selenium支持多语言(java\python\js\ruby) Appium原理 三个主…

基于小程序实现的查寝打卡系统

作者主页&#xff1a;Java码库 主营内容&#xff1a;SpringBoot、Vue、SSM、HLMT、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、小程序、安卓app等设计与开发。 收藏点赞不迷路 关注作者有好处 文末获取源码 技术选型 【后端】&#xff1a;Java 【框架】&#xff1a;ssm 【…

k-均值聚类

K均值聚类&#xff08;K-means clustering&#xff09;是一种常用的无监督学习方法&#xff0c;用于将一组数据点划分为K个簇&#xff08;cluster&#xff09;。 它的目标是将相似的数据点归到同一个簇中&#xff0c;同时使得不同簇之间的数据点尽可能不相似。K均值聚类算法的…

学习笔记记录ensp中防火墙配置(trust,unstrus,dmz 资源下载可用)

实验目的&#xff0c;通过配置防火墙控制相互之间的访问&#xff0c;拓扑图如下 资源已上传&#xff0c;注意lsw1和ar2的路由表到各个网段的路由表配置&#xff0c;通过防火墙来控制各个区域能否访问成功。 防火墙通过cloud2链接&#xff0c;方便登录网页配置防火墙策略。防火…

分享基于鸿蒙OpenHarmony的Unity团结引擎应用开发赛

该赛题旨在鼓励更多开发者基于OpenHarmony4.x版本&#xff0c;使用团结引擎创造出精彩的游戏与应用。本次大赛分为“创新游戏”与“创新3D 化应用”两大赛道&#xff0c;每赛道又分“大众组”与“高校组”&#xff0c;让不同背景的开发者同台竞技。无论你是游戏开发者&#xff…

操作系统—系统调用(实验)

文章目录 系统调用1.实验目标2.实验过程记录(1).理解系统调用接口(2).阅读argraw、argint、argaddr和argstr(3).理解系统调用的解耦合实现方式(4).wait系统调用的非阻塞选项实现(5).yield系统调用的实现 3.存在的问题及解决方案实验小结 系统调用 1.实验目标 阅读并了解xv6内核…

基于Python+Selenium+Pytest的Dockerfile如何写

使用 Dockerfile 部署 Python 应用程序与 Selenium 测试 在本文中&#xff0c;我们将介绍如何使用 Dockerfile 部署一个 Python 应用程序&#xff0c;同时利用 Selenium 进行自动化测试。我们将使用官方的 Python 运行时作为父镜像&#xff0c;并在其中安装所需的依赖项和工具…