Rust अभ्यास
Bank Account in Rust with Result
A struct, methods and your own error enum: deposits and withdrawals that can fail safely.
आप क्या सीखेंगे
- Methods that return Result
- An error enum with data
- Reporting errors
Operation → result
deposit(50)okwithdraw(500)error: need 500, have 150withdraw(120)ok, balance 30Every 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.
मुख्य बातें
- deposit rejects 0.
- withdraw rejects more than the balance.
- 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अभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज