Answer#
Rust never converts between types silently (an i32 is not a u64, a &str is not a String), so every place that expects a type checks it. The message always has two parts: what was expected and what was found. Read those first.
How to do it#
- Look at this function. It promises an
i32, but ends inx * 2;.
fn double(x: i32) -> i32 {
x * 2;
}
fn main() {
println!("{}", double(4));
}error[E0308]: mismatched types
--> src/main.rs:1:22
|
1 | fn double(x: i32) -> i32 {
| ------ ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | x * 2;
| - help: remove this semicolon to return this value
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0308`.- The semicolon turns the last line into a statement, so the function body has no value and its type is
(). Remove the semicolon.
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
println!("{}", double(4));
}8Other common causes and fixes#
expected String, found &str: call.to_string()orString::from(...).expected u64, found u32(or any two number types): convert on purpose withvalue as u64oru64::from(value);fromis only offered where no information can be lost.expected Option<T>, found T: wrap the value inSome(...).ifandelsebranches (ormatcharms) that produce different types: make them agree.
Common mistakes#
- Fixing the symptom with
aswhere the types differ for a reason, for example casting a possibly negativei32tousize. A negative value turns into a huge number. - Adding
returnto every line instead of understanding that the last expression without a semicolon is the value.
Run rustc --explain E0308 for the long explanation with more examples.