The Rust Programming Language
- Defining an Enum
- enum gives us a way of saying a value is one of a possible set of values
- Enum Values
- we can put data directly into each enum variant
- the name of each enum variant that we define also becomes a function
that constructs an instance of the enum
- each variant can have different types and amounts of associated data
- we can put any kind of data inside an enum variant
ex) strings, numeric types, structs, another enum, etc.
- we're able to define methods on enums using impl keyword
- The Option Enum and Its Advantabes Over Null Values
- The Option type encodes the very common scenario
in which a value could be something or it could be nothing
- eliminating the risk of incorrectly assuming a not-null value
helps you to be more confident in your code
fn main() {
let four = IpAddrKind::V4(127, 0, 0, 1);
let six = IpAddrKind::V6(String::from("::1"));
dbg!(four);
}
#[derive(Debug)]
enum IpAddrKind {
V4(u8, u8, u8, u8),
V6(String),
}
- The match Control Flow Construct
- Patterns That Bind to Values
fn main() {
value_in_cents(Coin::Quarter(UsState::Alaska));
}
#[derive(Debug)]
enum UsState {
Alabama,
Alaska,
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => {
println!("Lucky penny!");
1
}
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter(state) => {
println!("State quarter from {:?}", state);
25
}
}
}
- Matching with Option<T>
fn main() {
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
println!("{:?} {:?} {:?}", five, six, none);
}
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
- Matches Are Exhaustive
- Catch-all Patterns and the _ Placeholder
fn main() {
let dice_roll = 9;
match dice_roll {
3 => add_fancy_hat(),
7 => remove_fancy_hat(),
_ => reroll(),
}
}
fn add_fancy_hat() {}
fn remove_fancy_hat() {}
fn reroll() {}
- Concise Control Flow with if let
fn main() {
let config_max = Some(3u8);
// match config_max {
// Some(max) => println!("The maximum is configured to be {}", max),
// _ => (),
// }
if let Some(max) = config_max {
println!("The maximum is configured to be {}", max);
} else {
println!("hi");
}
}
- Summary
'Personal-Study > Rust' 카테고리의 다른 글
[Rust 문서 읽기] 8. Common Collections (일반적인 컬렉션) (0) | 2023.02.11 |
---|---|
[Rust 문서 읽기] 7. Managing Growing Projects with Packages, Crates, and Modules (모듈) (0) | 2023.02.11 |
[Rust 문서 읽기] 5. Using Structs to Structure Related Data (연관된 데이터들을 구조체로 다루기) (0) | 2023.02.05 |
[Rust 문서 읽기] 4. Understanding Ownership (소유권 이해하기) (0) | 2023.01.29 |
[Rust 문서 읽기] 3. Common Programming Concepts (보편적인 프로그래밍 개념) (0) | 2023.01.29 |
댓글