当前位置:网站首页>Enumeration and control flow operation in rust
Enumeration and control flow operation in rust
2022-06-27 19:57:00 【User 3147702】
1. introduction
Enumeration type for Java It's no stranger to programmers , It is a very useful tool for enumerating constant members . stay rust The same is true of China , And in rust in , Enumeration types are more commonly used than in other languages , In especial Option、Result And the enumeration types defined by the language itself , by rust It adds a very powerful and unique syntax feature .
2. Enumeration type
And java The types and values of enumerations are different in language enumerations ,rust Enumerations in focus on types , Enumeration members themselves do not correspond to specific values .
2.1 Definition of enumeration type
for example , The following enumeration types define IPv4 and IPv6 Two members :
enum IpAddrKind {
V4,
V6,
}
fn main() {
let four = IpAddrKind::V4;
let six = IpAddrKind::V6;
route(IpAddrKind::V4);
route(IpAddrKind::V6);
}
fn route(ip_kind: IpAddrKind) {}2.2 Enumerating types of data
In the example above , Defines an enumeration type , And create variables of corresponding types .
But we often not only want variables to reflect specific types , You also want variables to have specific values .
At this point, we can encapsulate the enumeration type and the specific value , Thus, a structure containing both types and values is obtained .
fn main() {
enum IpAddrKind {
V4,
V6,
}
struct IpAddr {
kind: IpAddrKind,
address: String,
}
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from("127.0.0.1"),
};
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from("::1"),
};
}further , We can go through rust To simplify the definition of the above structure :
fn main() {
enum IpAddr {
V4(String),
V6(String),
}
let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));
}thus , The data is directly attached to the enumeration type . Compared with the above composite type defined by structure , Directly attaching data to enumeration types can also define different types of data :
fn main() {
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));
}3. Special enumeration types Option
Option yes rust An enumeration defined by the standard library .Option The existence of , Try to solve the null pointer that drives countless software development engineers crazy 、 Empty reference problem .
3.1 Option The definition of
Option Is defined as follows :
enum Option<T> {
None,
Some(T),
}It looks very simple , If a function or expression wants to return a T Data of type , also T Data of type may be empty . Then use Option Encapsulation would be a better choice . because T If the data of type is null , The user ignores this , Will generate a program panic, This is usually what we don't want to see .
3.2 Option Creation of variables
You can get a Option The data of :
let x: Option<u32> = Some(2);
assert_eq!(x.is_some(), true);
let x: Option<u32> = None;
assert_eq!(x.is_some(), false);
let x: Option<u32> = None;
assert_eq!(x.is_none(), true);Once a return value is Option encapsulated , The user must process a value of None The situation of , This explicit handling , Avoid unexpected empty references 、 Generation of null pointer .
3.3 Option Data acquisition
To get Option Actual data in , There are many ways , Here is unwrap Method .
1. unwrap Method
unwarp Methods need to be guaranteed to have value , Once the value is None, Then the program will panic.
// If the value is None, be unwrap Will lead to panic
let x = Some("air");
assert_eq!(x.unwrap(), "air");2. unwrap_or Method
And unwrap The method is different ,unwrap_or Method allows you to pass a parameter , The duty of None when , Take this parameter as the return value .
assert_eq!(Some("car").unwrap_or("bike"), "car");
assert_eq!(None.unwrap_or("bike"), "bike");3. unwrap_or_else Method
unwrap_or Method allows us to provide a default return value , But more advanced is unwrap_or_else Method , It allows us to create a function or expression to determine when the value is None What is returned when .
let vec = vec![1,2,3];
let a: &i32 = vec.get(4).unwrap_or_else(||{
vec.get(0)
});4. control flow match
As in java In language , Enumeration type collocation switch-case It can make the code very simple and easy to maintain . stay Rust in , Through powerful control flow operators match A similar effect can be achieved with enumerations .
4.1 match Use
Here's one match Examples of control flow :
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => {
println!("Lucky penny!");
1
}
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}4.2 match Get enumeration value
When an enumeration has its enumeration data value , It can also be done match:
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter(state) => {
println!("State quarter from {:?}!", state);
25
}
}
}4.3 Option And match matching
With the above 4.2 An example section of , We can deal with it Option Type of data :
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None); This example defines a function , It gets a Option<i32> , If it contains a value , Add one . If there is no value , Function should return None value , Without trying to do anything .
4.4 General distribution mode
It should be noted that , If you want to use match control flow , Every type contained in an enumerated type must appear in match In block .
But sometimes , We want to have a model that can be used to replace all other situations , Similar to other languages switch Statement default keyword , stay Rust in , This feature is also supported , That's it _ Place holder :
let dice_roll = 9;
match dice_roll {
3 => add_fancy_hat(),
7 => remove_fancy_hat(),
_ => (),
}
fn add_fancy_hat() {}
fn remove_fancy_hat() {}5. if let control flow
A lot of times , We just want to simply get the value or expression corresponding to an enumeration , adopt match Expressions tend to appear too complex . here ,if let It might be a better choice , for example :
#[derive(Debug)]
enum UsState {
Alabama,
Alaska,
// --snip--
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
fn main() {
let coin = Coin::Penny;
let mut count = 0;
if let Coin::Quarter(state) = coin {
println!("State quarter from {:?}!", state);
} else {
count += 1;
}
}边栏推荐
- SQL Server - Window Function - 解决连续N条记录过滤问题
- C# 二维码生成、识别,去除白边、任意颜色
- 蓄力中台,用友iuap筑牢社会级企业数智化新底座
- Pointers and structs
- A simple calculation method of vanishing point
- 可靠的分布式锁 RedLock 与 redisson 的实现
- As a software engineer, give advice to young people (Part 2)
- One to one relationship
- Doctoral Dissertation of the University of Toronto - training efficiency and robustness in deep learning
- 多伦多大学博士论文 | 深度学习中的训练效率和鲁棒性
猜你喜欢

Crawl national laws and Regulations Database

crontab的学习随笔

【debug】平台工程接口调试

SQL Server - Window Function - 解决连续N条记录过滤问题

键入网址到网页显示,期间发生了什么?

429- binary tree (108. convert the ordered array into a binary search tree, 538. convert the binary search tree into an accumulation tree, 106. construct a binary tree from the middle order and post o

MySQL beginner benefits

binder hwbinder vndbinder

指针和结构体

MySQL表的增删改查(基础)
随机推荐
Function key input experiment based on stm32f103zet6 Library
On thread safety
UE4-Actor基础知识
Common shell script commands (4)
Is it safe to buy stocks and open an account on the account opening link of the securities manager? Ask the great God for help
Rust 中的枚举和控制流运算
SQL Server - Window Function - 解决连续N条记录过滤问题
One to one relationship
Leetcode 989. 数组形式的整数加法(简单)
在线文本按行批量反转工具
实战回忆录:从Webshell开始突破边界
【debug】平台工程接口调试
1029 Median
Bit.Store:熊市漫漫,稳定Staking产品或成主旋律
网络上开户买股票是否安全呢?刚接触股票,不懂求指导
Embracing cloud Nativity: Practice of Jiangsu Mobile order center
海底电缆探测技术总结
运算符的基础知识
1028 List Sorting
Leetcode 1381. 设计一个支持增量操作的栈