E0308
rust
type_error
ai_generated
true
error[E0308]: `match` arms have incompatible types note: expected `Result<(), MyError>` found `Result<(), OtherError>`
ID: rust/e0308-match-arm-different-types-with-generic
92%Fix Rate
83%Confidence
1Evidence
2023-10-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| rustc 1.74 | active | — | — | — |
| rustc 1.75 | active | — | — | — |
Root Cause
Different match arms return `Result` types with different error types, even if both implement `From` or `Into`.
generic中文
不同的 match 分支返回具有不同错误类型的 `Result` 类型,即使两者都实现了 `From` 或 `Into`。
Official Documentation
https://doc.rust-lang.org/stable/error_codes/E0308.htmlWorkarounds
-
90% success Use `.map_err()` on each arm to convert errors to a common type: `arm1.map_err(|e| MyError::from(e))`.
Use `.map_err()` on each arm to convert errors to a common type: `arm1.map_err(|e| MyError::from(e))`.
-
95% success Define a unified error enum that wraps both error types and implement `From` for each.
Define a unified error enum that wraps both error types and implement `From` for each.
中文步骤
在每个分支上使用 `.map_err()` 将错误转换为公共类型:`arm1.map_err(|e| MyError::from(e))`。
定义一个统一的错误枚举,包装两种错误类型,并为每种类型实现 `From`。
Dead Ends
Common approaches that don't work:
-
70% fail
Only fixes one arm; compiler still sees mismatch if the other arm has a different error type.
-
85% fail
Panics on error; not a proper fix for error handling.