enum

6 Enum

Enums allow you to define a type by enumerating its possible variants.

6.1 define and use

1
2
3
4
5
enum IpAddrKind {
V4,
V6,
}
let four = IpAddrKind::V4;

rust中的enum可以接收不通类型的参数

1
2
3
4
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}

6.2 Option Enum

Rust does not have nulls, but it does have an enum that can encode the concept of a value being present or absent.
This enum is Option.

6.3 match

1
2
3
4
5
6
7
8
let some_u8_value = 0u8;
match some_u8_value {
1 => println!("one"),
3 => println!("three"),
5 => println!("five"),
7 => println!("seven"),
_ => (),
}
  • However, the match expression can be a bit wordy in a situation in which we care about only one of the cases.
  • For this situation, Rust provides if let.

6.4 if let

1
2
3
4
5
6
7
8
9
10
if we only care about one of the case, we can use "if let"
let some_u8_value = Some(0u8);
match some_u8_value {
Some(3) => println!("three"),
_ => (),
}
等价于
if let Some(3) = some_u8_value {
println!("three");
}
© 2023 PLAYAROUND All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero