# 错误[E0308]：`if` 和 `else` 分支的类型不兼容

- **ID:** `rust/e0308-incompatible-types-in-if-and-else`
- **领域:** rust
- **类别:** type_error
- **错误码:** `E0308`
- **验证级别:** ai_generated
- **修复率:** 92%

## 根因

if-else 表达式的两个分支返回了不同的类型，Rust 的类型系统无法统一它们。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| rustc 1.60.0 | active | — | — |
| rustc 1.65.0 | active | — | — |
| rustc 1.72.0 | active | — | — |

## 解决方案

1. ```
   使用显式类型转换：`let x = if cond { 42_i32 } else { "hello".parse::<i32>().unwrap_or(0) };`
   ```
2. ```
   使用特征对象：`let x: Box<dyn std::fmt::Display> = if cond { Box::new(42) } else { Box::new("hello") };`
   ```
3. ```
   使用枚举：`enum MyEnum { Int(i32), Str(&'static str) } let x = if cond { MyEnum::Int(42) } else { MyEnum::Str("hello") };`
   ```

## 无效尝试

- **** — Type annotations don't magically convert types. The else branch still returns a &str, not an i32. (95% 失败率)
- **** — Return makes the branch diverge (never produce a value), so the types can still mismatch if the other branch has a different type. (75% 失败率)
- **** — Box<dyn Trait> requires both types to implement the same trait, but Box::new alone doesn't create a trait object. (85% 失败率)
