E0308 rust type_error ai_generated true

error[E0308]: `if` and `else` have incompatible types

ID: rust/e0308-incompatible-types-in-if-and-else

Also available as: JSON · Markdown · 中文
92%Fix Rate
88%Confidence
1Evidence
2023-03-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
rustc 1.60.0 active
rustc 1.65.0 active
rustc 1.72.0 active

Root Cause

The if and else branches of an if-else expression return different types, which Rust's type system cannot unify.

generic

中文

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

Official Documentation

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

Workarounds

  1. 80% success Use explicit type conversion: `let x = if cond { 42_i32 } else { "hello".parse::<i32>().unwrap_or(0) };`
    Use explicit type conversion: `let x = if cond { 42_i32 } else { "hello".parse::<i32>().unwrap_or(0) };`
  2. 90% success Use a trait object: `let x: Box<dyn std::fmt::Display> = if cond { Box::new(42) } else { Box::new("hello") };`
    Use a trait object: `let x: Box<dyn std::fmt::Display> = if cond { Box::new(42) } else { Box::new("hello") };`
  3. 95% success Use an enum: `enum MyEnum { Int(i32), Str(&'static str) } let x = if cond { MyEnum::Int(42) } else { MyEnum::Str("hello") };`
    Use an enum: `enum MyEnum { Int(i32), Str(&'static str) } let x = if cond { MyEnum::Int(42) } else { MyEnum::Str("hello") };`

中文步骤

  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") };`

Dead Ends

Common approaches that don't work:

  1. 95% fail

    Type annotations don't magically convert types. The else branch still returns a &str, not an i32.

  2. 75% fail

    Return makes the branch diverge (never produce a value), so the types can still mismatch if the other branch has a different type.

  3. 85% fail

    Box<dyn Trait> requires both types to implement the same trait, but Box::new alone doesn't create a trait object.