rust type_error ai_generated true

error[E0308]: mismatched types

ID: rust/e0308-mismatched-types

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Expected one type but got another. Very common with String vs &str, Option<T> vs T, etc.

generic

Workarounds

  1. 92% success Use .into(), .as_ref(), .to_string(), or .as_str() for standard conversions
    let s: String = my_str.into();

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

  2. 88% success Handle Option/Result with unwrap_or, map, or pattern matching
    // Pattern matching:
    match get_value() {
        Some(v) => println!("Got: {v}"),
        None => println!("No value"),
    }
    // unwrap_or for defaults:
    let val = opt.unwrap_or(0);
    // map to transform inner value:
    let len: Option<usize> = name.map(|s| s.len());

    Sources: https://doc.rust-lang.org/book/ch06-02-match.html

  3. 90% success Check return type annotation matches the actual returned value
    // Wrong: function says it returns String but returns &str
    fn name() -> String {
        "hello"  // error: expected String, found &str
    }
    // Fix: convert with .to_string() or .into():
    fn name() -> String {
        "hello".to_string()
    }

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

Dead Ends

Common approaches that don't work:

  1. Use as to cast between incompatible types 72% fail

    as is for numeric casts, not type conversions

  2. Use unsafe transmute 95% fail

    Undefined behavior, never correct for type mismatches

Error Chain

Leads to:
Preceded by: