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
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`.
官方文档
https://doc.rust-lang.org/stable/error_codes/E0308.html解决方案
-
在每个分支上使用 `.map_err()` 将错误转换为公共类型:`arm1.map_err(|e| MyError::from(e))`。
-
定义一个统一的错误枚举,包装两种错误类型,并为每种类型实现 `From`。
无效尝试
常见但无效的做法:
-
70% 失败
Only fixes one arm; compiler still sees mismatch if the other arm has a different error type.
-
85% 失败
Panics on error; not a proper fix for error handling.