rust type_error ai_generated true

error[E0308]: `match` arms have incompatible types

ID: rust/e0308-match-arms-different-types

Also available as: JSON · Markdown
92%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Match expression arms return different types. All arms must return the same type.

generic

Workarounds

  1. 95% success Return the same type from all arms, or use an enum to unify them
    enum Shape { Circle(f64), Square(f64) }
    match input {
        "circle" => Shape::Circle(r),
        _ => Shape::Square(s),
    }

    Sources: https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html

  2. 85% success Use impl Trait or Box<dyn Trait> if arms return different types implementing same trait
    Use impl Trait or Box<dyn Trait> if arms return different types implementing same trait

    Sources: https://doc.rust-lang.org/book/ch17-02-trait-objects.html

Dead Ends

Common approaches that don't work:

  1. Use Box<dyn Any> to erase types 80% fail

    Loses all type safety and requires downcasting

Error Chain

Frequently confused with: