Rust — E0308 mismatched types expected X found Y
Resolve E0308 mismatched type errors by aligning types, handling Option and Result, and fixing references versus values.
Symptoms
- error[E0308]: mismatched types, expected `i32`, found `i64`
- expected &str found String or vice versa
- Expected Option<T> found T after unwrapping incorrectly
- A branch returns a different type than another
Possible causes
- Integer or float types differ and need conversion
- A String is used where &str is expected or the reverse
- An expression returns T where Option<T> or Result<T, E> is expected
- Branches of an if or match return different types
Diagnosis steps
Read both expected and found types
cargo build 2>&1 | head -30Interpretation
The compiler prints the expected and actual types, which shows whether a conversion, deref or wrapping is needed.
Convert integers explicitly
let x: i64 = i as i64;Interpretation
Rust does not implicitly convert numeric types, so explicit casts or From conversions are required.
Align Option and Result
let v = opt.ok_or(Error::Missing)?;Interpretation
Wrapping or unwrapping Option and Result with the right combinators matches the expected type.
Root cause
The expression produced a type different from the one the context required, whether a numeric mismatch, a reference versus owned mismatch, or a missing Option or Result wrapper.
Fix
Convert values explicitly, borrow or clone to match reference expectations, and wrap or unwrap Option and Result with the appropriate combinators so both branches and expressions agree.
Verify the fix
Rebuild and confirm the type error is gone, then run tests to confirm conversions preserved the intended values and error handling.
Symptom walkthrough
The compiler reports E0308, mismatched types, naming the expected and found types. The mismatch might be two integer widths, a String where a &str is wanted, a bare value where an Option or Result is expected, or two branches of a conditional returning different types. Because Rust does not coerce implicitly, the exact conversion must be written.
Fix in practice
Add an explicit conversion or cast for numeric differences, borrow or clone to match reference expectations, and use the combinators such as ok_or, map and unwrap_or to move between Option, Result and plain values. Make both sides of a branch agree on one type.
Verification
Rebuild and confirm the error is gone, then run the tests and confirm the conversions preserved the intended values and that error cases are handled. Correct data plus a clean build confirms the fix.
Diagnostic commands
Check the behavior with commands like these:
cargo build 2>&1 | head -30
let x: i64 = i as i64;
let v = opt.ok_or(Error::Missing)?;