mismatched types
The “mismatched types” error in Rust occurs when the compiler finds a value of one type where a different type is expected. Rust’s strong static type system catches every type inconsistency at compile time, preventing runtime type errors.
What It Means
Rust checks every expression and assignment against its expected type. If you try to assign an i32 to a u32 variable, pass a String where &str is expected, or return the wrong type from a function, the compiler reports “mismatched types” along with the expected and found types.
Why It Happens
- You assigned a value of one numeric type where another is expected (e.g.,
i32vsu64). - A function returns one type but the signature declares a different type.
- You are using
Stringwhere&stris expected (or vice versa). - An arithmetic operation produces a different type than you assumed.
- You wrapped a value in
Some()when the expected type is the inner value, or vice versa. - The
?operator changes the error type in a function returningResult.
How to Fix It
1. Use the as keyword for numeric conversion
Rust does not implicitly convert numeric types:
let x: i32 = 10;
let y: u64 = x as u64; // explicit cast required
let z: f64 = x as f64;2. Use into or from for type conversion
Implement the From trait for custom type conversions:
let s: String = String::from("hello");
let slice: &str = &s; // &String coerces to &str
let num: u64 = 42u32.into(); // using Into trait
3. Check function return types
Ensure the returned value matches the declared return type:
// Error: mismatched types — expected u32, found i32
fn get_value() -> u32 {
-5 // i32 cannot be returned as u32
}
// Fix: use u32 or handle negative case
fn get_value() -> u32 {
5u32
}4. Use the turbofish syntax for generic functions
When calling generic functions, you may need to specify the type:
let num: u64 = "42".parse().unwrap(); // type inference works here
// But sometimes you need turbofish:
let num = "42".parse::<u64>().unwrap();5. Handle Result and Option correctly
A common mismatch is forgetting to unwrap a Result or Option:
fn read_file() -> String {
std::fs::read_to_string("file.txt")
// Error: mismatched types — found Result<String>, expected String
}
// Fix: add error handling
fn read_file() -> Result<String, std::io::Error> {
std::fs::read_to_string("file.txt")
}FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro