Untitled
unknown
rust
4 years ago
2.8 kB
13
Indexable
#![allow(dead_code)]
use std::io::{self, Write};
#[derive(Debug)]
enum OperationError {
NegativeAmount,
InsufficientFunds,
MaxDepositAmount,
IncorrectWithdrawAmount,
}
trait AccountOperation {
fn deposit(&mut self, amount: f64) -> Result<(), OperationError>;
fn withdraw(&mut self, amount: f64) -> Result<(), OperationError>;
}
struct Account {
balance: f64,
}
impl Account {
fn new(initial_balance: f64) -> Result<Self, OperationError> {
let mut account = Account { balance: 0.0 };
account.deposit(initial_balance)?;
Ok(account)
}
}
impl AccountOperation for Account {
fn deposit(&mut self, amount: f64) -> Result<(), OperationError> {
if amount <= 0.0 {
return Err(OperationError::NegativeAmount);
}
self.balance += amount;
Ok(())
}
fn withdraw(&mut self, amount: f64) -> Result<(), OperationError> {
if amount <= 0.0 {
return Err(OperationError::NegativeAmount);
}
if self.balance < amount {
return Err(OperationError::InsufficientFunds);
}
self.balance -= amount;
Ok(())
}
}
struct ABCBankAccount {
account: Account,
bank_charges: f64,
}
impl ABCBankAccount {
fn new(initial_amount: f64, bank_charges: f64) -> Result<Self, OperationError> {
Ok(Self {
account: Account::new(initial_amount)?,
bank_charges,
})
}
fn deposit(&mut self, amount: f64) -> Result<(), OperationError> {
if self.account.balance + amount > 2000.0 {
return Err(OperationError::MaxDepositAmount);
}
self.account.deposit(amount)?;
Ok(())
}
fn withdraw(&mut self, amount: f64) -> Result<(), OperationError> {
if amount as i64 % 5 != 0 {
return Err(OperationError::IncorrectWithdrawAmount);
}
self.account.withdraw(amount + self.bank_charges)?;
Ok(())
}
}
fn main() -> Result<(), OperationError> {
let mut pooja_account = ABCBankAccount::new(100.0, 0.5)?;
let mut buffer = String::new();
println!("Current Balance: {}", pooja_account.account.balance);
loop {
print!("Please input the withdraw amount: ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut buffer).unwrap();
let withdraw_amount: f64 = buffer.trim().parse().expect("Please provide a number");
match pooja_account.withdraw(withdraw_amount) {
Ok(()) => {
println!(
"Balance after transaction: {}",
pooja_account.account.balance
);
}
Err(err) => {
println!("Error: {:?}", err);
}
}
buffer.clear();
}
}Editor is loading...