// 自定义错误类型
#[derive(Debug)]
pub struct FinancialError {
pub function_name: &'static str,
pub reason: String,
}
impl std::fmt::Display for FinancialError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Error in function {}: {}", self.function_name, self.reason)
}
}
impl std::error::Error for FinancialError {}
// 处理金融交易数据的函数
pub fn process_transaction(amount: f64, account_balance: f64) -> Result<f64, FinancialError> {
if amount < 0.0 {
return Err(FinancialError {
function_name: "process_transaction",
reason: "Transaction amount cannot be negative".to_string(),
});
}
if amount > account_balance {
return Err(FinancialError {
function_name: "process_transaction",
reason: "Insufficient balance".to_string(),
});
}
Ok(account_balance - amount)
}
pub fn calculate_interest(principal: f64, rate: f64, years: u32) -> Result<f64, FinancialError> {
if rate < 0.0 || rate > 1.0 {
return Err(FinancialError {
function_name: "calculate_interest",
reason: "Interest rate should be between 0 and 1".to_string(),
});
}
if years == 0 {
return Err(FinancialError {
function_name: "calculate_interest",
reason: "Years cannot be zero".to_string(),
});
}
let interest = principal * rate * (years as f64);
Ok(interest)
}
// 示例调用代码
fn main() {
let account_balance = 1000.0;
let transaction_amount = 200.0;
let principal = 500.0;
let interest_rate = 0.05;
let years = 3;
let new_balance = process_transaction(transaction_amount, account_balance);
match new_balance {
Ok(balance) => println!("New balance: {}", balance),
Err(e) => eprintln!("Error: {}", e),
}
let interest = calculate_interest(principal, interest_rate, years);
match interest {
Ok(int) => println!("Interest: {}", int),
Err(e) => eprintln!("Error: {}", e),
}
}