MST

星途 面试题库

面试题:Rust中Result类型在错误处理中的应用

在Rust中,`Result`类型常被用于错误处理。请编写一个函数,该函数接收两个整数作为参数,尝试将它们相除,并使用`Result`类型返回结果或错误。若除数为0,返回一个自定义的错误类型,描述除数不能为零的错误。
22.4万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
// 自定义错误类型
#[derive(Debug)]
struct DivisionByZeroError;

impl std::fmt::Display for DivisionByZeroError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "除数不能为零")
    }
}

impl std::error::Error for DivisionByZeroError {}

fn divide(a: i32, b: i32) -> Result<i32, DivisionByZeroError> {
    if b == 0 {
        Err(DivisionByZeroError)
    } else {
        Ok(a / b)
    }
}