当前位置:网站首页>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;
}
}边栏推荐
猜你喜欢
随机推荐
网络上开户买股票是否安全呢?刚接触股票,不懂求指导
UE4-Actor基础知识
mime.type文件内容
Memoirs of actual combat: breaking the border from webshell
One to one relationship
redis集群系列二
Data intelligence enters the "deep water area", and data governance is the key
基础数据类型和复杂数据类型
1028 List Sorting
Observable, reliable: the first shot of cloudops series Salon of cloud automation operation and maintenance
移动低代码开发专题月 | 可视化开发 一键生成专业级源码
Doctoral Dissertation of the University of Toronto - training efficiency and robustness in deep learning
1023 Have Fun with Numbers
Rust 中的枚举和控制流运算
实战回忆录:从Webshell开始突破边界
从指令交读掌握函数调用堆栈详细过程
ABAP随笔-面试回忆 望大家 需求不增 人天飙升
通过 Cargo 管理 Rust 项目
Substrate及波卡一周技术更新速递 20220425 - 20220501
Error reported by Huada MCU Keil_ Weak's solution









