Rust 연습 문제

Bank Account in Rust with Result

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

  • 초급
  • 5분 분량
  • 실행 가능한 예제 1개
배울 내용
  • 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.

핵심 포인트

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

실행 가능한 Rust 예제

Rust
코드 실행 →
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);
}
이 예제의 실행 버튼 만들기 코드 실행 결과
ok
error: need 500, have 150
error: amount must be positive
ok
Ada has 30

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: Traits →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지