MST
星途 面试题库

面试题:Rust函数返回值类型与自定义错误处理机制的深度融合

设计一个Rust库,其中包含多个相互关联的函数,用于处理复杂的金融交易数据。这些函数需要返回不同类型的值,并且要自定义一套错误处理机制,该机制能够提供详细的错误上下文信息(例如发生错误的函数名、具体错误原因等)。展示如何在库函数中使用这个自定义错误处理机制,以及外部调用者如何方便地处理这些错误,同时要考虑错误的类型转换和兼容性。请写出完整的库代码结构以及示例调用代码。
28.1万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
// 自定义错误类型
#[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),
    }
}