E0308 rust type_error ai_generated true

错误[E0308]:`match` 分支的类型不兼容 注意:期望 `Result<(), MyError>` 发现 `Result<(), OtherError>`

error[E0308]: `match` arms have incompatible types note: expected `Result<(), MyError>` found `Result<(), OtherError>`

ID: rust/e0308-match-arm-different-types-with-generic

其他格式: JSON · Markdown 中文 · English
92%修复率
83%置信度
1证据数
2023-10-05首次发现

版本兼容性

版本状态引入弃用备注
rustc 1.74 active
rustc 1.75 active

根因分析

不同的 match 分支返回具有不同错误类型的 `Result` 类型,即使两者都实现了 `From` 或 `Into`。

English

Different match arms return `Result` types with different error types, even if both implement `From` or `Into`.

generic

官方文档

https://doc.rust-lang.org/stable/error_codes/E0308.html

解决方案

  1. 在每个分支上使用 `.map_err()` 将错误转换为公共类型:`arm1.map_err(|e| MyError::from(e))`。
  2. 定义一个统一的错误枚举,包装两种错误类型,并为每种类型实现 `From`。

无效尝试

常见但无效的做法:

  1. 70% 失败

    Only fixes one arm; compiler still sees mismatch if the other arm has a different error type.

  2. 85% 失败

    Panics on error; not a proper fix for error handling.