今天我们来看看一个类似的概念 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 howSome
represents a value being present, whileNone
indicates the absence of a value. Additionally, we learned how to use theunwrap_or
method to handle situations where we need to extract a value from anOption
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 usematch
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 calledarea()
.Shape
枚举是用一个名为area()
的方法实现的。 - The
area()
method takes a reference toself
(the enum instance) and returns af64
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
andsquare
) 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 presentSome
在存在值时使用none
is used when when a value is absentnone
在缺少值时使用- 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 integersnumbers
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()
returnsSome(&first)
, wherefirst
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 offirst
and wraps it in anotherSome
, effectively unwrapping the reference.
如果Option是Some
,它提取first
的值并将其包装在另一个Some
中,有效地展开引用。 - If the Option is
None
, indicating an empty slice, it returnsNone
.
如果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 ofnumber
.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 pattern1
, the message "It's one!" is printed.
如果number
匹配模式1
,则消息“It's one!”是印刷的。 - If
number
matches the pattern2
, the message "It's two!" is printed.
如果number
匹配模式2
,则消息“It's two!”是印刷的。 - If
number
matches the patterns3
or4
, the message "It's three or four!" is printed.
如果number
匹配模式3
或4
,则消息“是三或四!”是印刷的。 - If
number
matches the pattern8
, 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. Ifnumber
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
is5
, 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!”是印刷的。