Mismatched types
Quick Answer
Match the expected type exactly: add a conversion (as, .into(), .to_string()), fix the return statement, or adjust the function signature.
One of the most frequent Rust compiler errors — a value of one type was used where a different type was expected. Covers function argument mismatches, return type mismatches, and operator operand mismatches.
- 1Returning a different type than declared in the function signature
- 2Passing &str where String is expected (or vice versa)
- 3Using integer literals without specifying the expected integer type
Fix 1
Use .into() or explicit conversion
fn greet(name: String) -> String {
format!("Hello, {}!", name)
}
// &str → String
let s: String = "hello".to_string(); // or "hello".into()
greet(s);Why this works
.into() calls From/Into trait implementations to convert between compatible types without requiring explicit type annotations.
Fix 2
Match the return type
fn parse_age(s: &str) -> Result<u32, std::num::ParseIntError> {
s.trim().parse::<u32>() // return type matches
}Why this works
Annotating the parse() call with the target type (::<u32>) resolves the type ambiguity and matches the declared return type.
fn double(n: i32) -> i32 { n * 2 }
double("5"); // error[E0308]: mismatched types, expected i32, found &strlet x: u8 = 255u8; // explicit suffix let y = 255_u8; // underscore suffix
Rust Compiler Error Index
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev