MST

星途 面试题库

面试题:Rust中自定义错误类型与Result类型的深度融合

定义一个复杂的Rust程序,其中包含自定义的错误类型层次结构(例如,有一个基础错误类型,多个派生错误类型)。编写多个函数,这些函数根据不同的业务逻辑返回不同的自定义错误类型,通过`Result`类型进行处理和传播。展示如何在不同模块间共享这些错误类型,以及如何实现错误的序列化和反序列化。
48.4万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
// 定义错误类型模块
mod errors {
    use serde::{Deserialize, Serialize};

    // 基础错误类型
    #[derive(Debug, Serialize, Deserialize)]
    pub enum BaseError {
        Other(String),
    }

    // 派生错误类型1
    #[derive(Debug, Serialize, Deserialize)]
    pub struct ErrorType1 {
        pub msg: String,
    }
    impl From<ErrorType1> for BaseError {
        fn from(e: ErrorType1) -> Self {
            BaseError::Other(e.msg)
        }
    }

    // 派生错误类型2
    #[derive(Debug, Serialize, Deserialize)]
    pub struct ErrorType2 {
        pub code: i32,
    }
    impl From<ErrorType2> for BaseError {
        fn from(e: ErrorType2) -> Self {
            BaseError::Other(format!("Error code: {}", e.code))
        }
    }
}

// 使用错误类型的模块
mod business_logic {
    use super::errors::{BaseError, ErrorType1, ErrorType2};
    use serde::{Deserialize, Serialize};

    // 函数1,返回ErrorType1
    pub fn function1() -> Result<(), ErrorType1> {
        Err(ErrorType1 {
            msg: "Function 1 error".to_string(),
        })
    }

    // 函数2,返回ErrorType2
    pub fn function2() -> Result<(), ErrorType2> {
        Err(ErrorType2 { code: 42 })
    }

    // 函数3,传播错误
    pub fn function3() -> Result<(), BaseError> {
        function1().map_err(|e| e.into())?;
        function2().map_err(|e| e.into())
    }
}

fn main() {
    use business_logic::{function1, function2, function3};
    use errors::BaseError;
    use serde_json;

    // 处理function1的错误
    match function1() {
        Ok(_) => println!("Function 1 succeeded"),
        Err(e) => println!("Function 1 failed: {:?}", e),
    }

    // 处理function2的错误
    match function2() {
        Ok(_) => println!("Function 2 succeeded"),
        Err(e) => println!("Function 2 failed: {:?}", e),
    }

    // 处理function3的错误
    match function3() {
        Ok(_) => println!("Function 3 succeeded"),
        Err(e) => println!("Function 3 failed: {:?}", e),
    }

    // 错误序列化
    let error_type1 = ErrorType1 {
        msg: "Serialized error".to_string(),
    };
    let serialized = serde_json::to_string(&error_type1).expect("Serialization failed");
    println!("Serialized: {}", serialized);

    // 错误反序列化
    let deserialized: ErrorType1 = serde_json::from_str(&serialized).expect("Deserialization failed");
    println!("Deserialized: {:?}", deserialized);
}
  1. 错误类型层次结构:在errors模块中定义了BaseError作为基础错误类型,ErrorType1ErrorType2作为派生错误类型,并实现了从派生类型到基础类型的转换。
  2. 函数返回不同错误类型:在business_logic模块中定义了function1function2分别返回ErrorType1ErrorType2function3则演示了错误的传播。
  3. 模块间共享错误类型:通过mod关键字定义模块,并使用use关键字在不同模块间共享错误类型。
  4. 错误的序列化和反序列化:使用serde库及其SerializeDeserialize trait 实现了错误类型的序列化和反序列化,示例中使用serde_json进行JSON格式的序列化和反序列化。