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