# Sugar
## Week 0C
----
## Introduction
+ 語法糖 Syntactic Sugar
+ 簡化語法結構
+ 增加程式碼的可讀性
+ 但功能本身並沒有增加
---
# Structures
----
## 宣告結構定義
```rust=
struct User {
active: bool,
user_name: String,
email: String,
sign_in_count: u64,
}
```
----
## 宣告結構實體
```rust=
let mut user1 = User {
active: true,
user_name: String::from("Apple"),
email: String::from("apple12345@example.com"),
sign_in_count: 0,
};
```
----
## 把結構印出來
在宣告前面加上 `#[derive(Debug)]`
<div style="font-size: 0.895em">
```rust=
#[derive(Debug)]
struct User {
user_name: String,
email: String,
}
let u: User = ...;
println!("{u:?}")
// user: User { user_name: "apple", email: "apple@example.com" }
```
</div>
----
## 修改欄位
```rust=
let mut user1 = User { ... };
user1.email = String::from("banana13579@gmail.com");
```
----
## 初始化語法糖
```rust=
struct User {
user_name: String,
email: String,
}
fn init_user(user_name: String, email: String) -> User {
return User { user_name, email };
}
```
----
## 無欄位名稱的結構
```rust=
struct Point(i32, i32);
struct Color(u8, u8, u8);
let p = Point(21, 35);
let c = Color(12, 34, 56);
println!("Coord({}, {})", p.0, p.1);
println!("RGB({}, {}, {})", c.0, c.1, c.2);
```
----
## 蝦米都沒有的結構
```rust=
struct WTF;
let wtf = WTF;
```
---
# Enumerations
----
## 基本語法
```rust=
enum Fruits {
Apple,
Banana,
Cherry,
}
let fruit = Fruits::Apple;
match fruit {
Fruits::Apple => println!("It's Apple!"),
Fruits::Banana => println!("It's Banana!"),
Fruits::Cherry => println!("It's Cherry!"),
}
```
----
## Option
+ `Option<T>` 是個內建的 Enum
```rust
let b: Option<u8> = Some(16);
```
+ 在 `Option` 裡面就可以放 `None` 了
```rust
let a: Option<u8> = None;
```
----
## 使用 match 取值
+ 在 match 取值裡面,會強制要求你考慮 None 的情況
```rust=
let a: Option<u8> = None;
let b: Option<u8> = Some(16);
let c = match a {
Some(val) => val,
None => 255,
};
```
----
## if let 語法糖
```rust=
let config_max = Some(3f32);
match config_max {
Some(max) => println!("最大值被設為 {max}"),
_ => (),
}
```
```rust=
let config_max = Some(3f32);
if let Some(max) = config_max {
println!("最大值被設為 {max}")
}
```
---
# Other
----
## 神秘數字
+ `3u8` 表示一個 `u8` 整數,其值為 3
+ 同理也有 `7i16`, `3.14f32`, `94.87f64` 等數值
----
## dbg!
```rust=
struct Rectangle {
width: u32,
height: u32,
}
let scale = 2;
let rect1 = Rectangle {
width: dbg!(30 * scale),
height: 50,
};
```
{"metaMigratedAt":"2023-06-18T00:31:28.452Z","metaMigratedFrom":"YAML","title":"Week 0C - Sugar","breaks":true,"description":"地獄貓旅行團第 12 週心得分享","slideOptions":"{\"transition\":\"slide\"}","contributors":"[{\"id\":\"c7cbb212-2c41-4dfa-8d85-f8e7fa769bf1\",\"add\":3148,\"del\":547}]"}