Day 7:第四週總結練習
學習目標
- 綜合運用 struct / enum / Option / Result
- 設計一個帶錯誤處理的小型資料模型
今日重點
本週回顧
- struct:定義資料結構、欄位、元組結構
- impl:方法(&self / &mut self / self)、關聯函式(::new)
- enum:攜帶不同型別資料的變體
- match / if let 模式匹配
- Option:安全的可空性
- Result:可失敗的運算 + 自訂錯誤
綜合練習:銀行帳戶系統
#[derive(Debug)]
enum AccountError {
InsufficientFunds { balance: f64, requested: f64 },
NegativeAmount,
NotFound,
}
struct Account {
owner: String,
balance: f64,
}
impl Account {
fn new(owner: String) -> Account {
Account { owner, balance: 0.0 }
}
fn deposit(&mut self, amount: f64) -> Result<(), AccountError> {
if amount < 0.0 {
return Err(AccountError::NegativeAmount);
}
self.balance += amount;
Ok(())
}
fn withdraw(&mut self, amount: f64) -> Result<(), AccountError> {
if amount < 0.0 {
return Err(AccountError::NegativeAmount);
}
if amount > self.balance {
return Err(AccountError::InsufficientFunds {
balance: self.balance,
requested: amount,
});
}
self.balance -= amount;
Ok(())
}
fn get_balance(&self) -> f64 { self.balance }
}
fn main() {
let mut acc = Account::new(String::from("Alice"));
acc.deposit(100.0).unwrap();
acc.withdraw(30.0).unwrap();
match acc.withdraw(500.0) {
Ok(_) => println!("ok"),
Err(e) => println!("Error: {:?}", e),
}
println!("Balance: {}", acc.get_balance());
}
挑戰
- 加一個
transfer(&mut self, other: &mut Account, amount: f64) -> Result<(), AccountError>方法,讓帳戶間轉帳,注意要檢查餘額。 - 思考:為什麼 deposit/withdraw 用
Result而不是直接 panic?
自我檢查
- 能設計帶錯誤的資料模型
- 能把 struct + impl + enum + Result 串起來
- 理解「用結果類型表達可失敗」的風格
- 對建構自己的 Rust 程式有信心
週總結
你已能建構自己的資料型別並處理錯誤。接下來進入泛型與特徵(Rust 抽象能力的核心)。