Bài tập Rust

Bank Account in Rust with Result

A struct, methods and your own error enum: deposits and withdrawals that can fail safely.

  • Cơ bản
  • Đọc trong 5 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • Methods that return Result
  • An error enum with data
  • Reporting errors
Operation → result
deposit(50)ok
withdraw(500)error: need 500, have 150
withdraw(120)ok, balance 30

Every operation can succeed or fail

This exercise combines a struct, methods and error handling. Each operation returns a Result, and the error enum says exactly what went wrong.

deposit rejects an amount of 0 and withdraw rejects an amount larger than the balance, so the balance can never become invalid. The InsufficientFunds variant carries the numbers needed for a useful message. Ok(()) means success with no value to return.

Những điểm quan trọng

  1. deposit rejects 0.
  2. withdraw rejects more than the balance.
  3. The balance can never become invalid.

Ví dụ Rust chạy được

Rust
Chạy code →
main.rs
enum BankError {
    InvalidAmount,
    InsufficientFunds { needed: u64, available: u64 },
}

impl BankError {
    fn message(&self) -> String {
        match self {
            BankError::InvalidAmount => String::from("amount must be positive"),
            BankError::InsufficientFunds { needed, available } => format!("need {needed}, have {available}"),
        }
    }
}

struct Account {
    owner: String,
    balance: u64,
}

impl Account {
    fn deposit(&mut self, amount: u64) -> Result<(), BankError> {
        if amount == 0 {
            return Err(BankError::InvalidAmount);
        }
        self.balance += amount;
        Ok(())
    }

    fn withdraw(&mut self, amount: u64) -> Result<(), BankError> {
        if amount > self.balance {
            return Err(BankError::InsufficientFunds { needed: amount, available: self.balance });
        }
        self.balance -= amount;
        Ok(())
    }
}

fn report(result: Result<(), BankError>) {
    match result {
        Ok(()) => println!("ok"),
        Err(error) => println!("error: {}", error.message()),
    }
}

fn main() {
    let mut account = Account { owner: String::from("Ada"), balance: 100 };
    report(account.deposit(50));
    report(account.withdraw(500));
    report(account.deposit(0));
    report(account.withdraw(120));
    println!("{} has {}", account.owner, account.balance);
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
ok
error: need 500, have 150
error: amount must be positive
ok
Ada has 30

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Traits →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách