Sub topic 4
Fixing mismatched types
This chapter covers error E0308, "mismatched types". It assumes you can read the parts of a rustc diagnostic (code, message, span, labels, help) and can run cargo check. It also assumes you know Rust's basic types, Option, Result, and String versus &str.
What E0308 means
Rust checks that every expression has the type its context demands. A function argument, a let with an annotation, a return value, and both branches of an if each carry an expected type. E0308 appears when the expression's actual type differs from the expected one.
Rust does not convert between types silently, apart from a few cases such as deref coercion (&String to &str). Each fix therefore changes one of two things: the value, or the type that was expected.
Every E0308 diagnostic gives you an expected type and a found type. Read those two first:
expected `i32`, found `()`The rest of the diagnostic explains where the expectation came from. Look for secondary labels such as "expected due to this" or "implicitly returns ()".
Case 1: found `()` because of a trailing semicolon
A block's value is its last expression. A semicolon turns that expression into a statement, so the block's value becomes (), the unit type.
fn double(x: i32) -> i32 {
x * 2;
}
fn main() {
println!("{}", double(4));
}rustc reports:
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 valueFollow the help and remove the semicolon:
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
println!("{}", double(4));
}This is the one E0308 case where the suggestion is almost always right. You can also write return x * 2;, which suits an early exit but is unusual as the final line.
Case 2: number types do not convert on their own
Rust treats u32 and u64 as unrelated types, even though every u32 fits in a u64.
fn main() {
let small: u32 = 7;
let big: u64 = small;
println!("{big}");
}The error says expected u64, found u32`, and the help suggests .into()`. You have three ways to convert, and they behave differently:
| Method | Behavior | Use when |
|---|---|---|
| `u64::from(small)` | Compiles only if the conversion can never lose data | Widening, such as `u32` to `u64` |
| `u8::try_from(n)` | Returns `Result`, with `Err` if the value does not fit | Narrowing, where the value may be out of range |
| `n as u8` | Truncates or wraps silently | You want C-style behavior and have checked the range |
fn main() {
let small: u32 = 7;
let big: u64 = u64::from(small);
let wide: u32 = 300;
let narrow = u8::try_from(wide);
println!("{big} {narrow:?} {}", wide as u8);
}This prints 7 Err(TryFromIntError(())) 44. The value 300 does not fit in a u8, so try_from reports an error. The as cast keeps only the low 8 bits, which gives 44, and nothing warns you. Prefer from and try_from, and use as only when you accept that wraparound.
Mixing integers and floats in arithmetic, such as i32 + f64, produces a related error, E0277. That case is covered in the chapter on trait bounds.
Case 3: `String` versus `&str`
String is an owned, growable string. &str is a borrowed view into string data. A string literal has type &'static str.
fn greet(name: String) {
println!("Hello, {name}");
}
fn main() {
greet("Ferris");
}The error is expected String, found &str``. You can fix it in two ways:
- Convert at the call site:
greet("Ferris".to_string()). This allocates a newString. - Change the function to take
&str:fn greet(name: &str). Callers can then pass a literal, or&my_string, which deref coercion turns into&str.
fn greet(name: &str) {
println!("Hello, {name}");
}
fn main() {
let owned = String::from("Ada");
greet("Ferris");
greet(&owned);
}Option 2 is usually better. A function that only reads the text has no reason to demand ownership of it.
Case 4: a wrapped value where a plain value is expected
Methods such as Vec::first, str::parse, and HashMap::get return Option or Result, because they can fail. Using the result directly gives E0308.
fn main() {
let nums = vec![10, 20, 30];
let first: i32 = nums.first();
println!("{first}");
}The error is expected i32, found Option<&i32>`. Note that the found type is Option<&i32>. Two things are wrong, the Option` wrapper and the reference inside it. Choose how to handle the missing case, then fix both:
fn main() {
let nums = vec![10, 20, 30];
// Default when empty. The * copies the i32 out of the reference.
let a: i32 = *nums.first().unwrap_or(&0);
// Handle both outcomes explicitly.
match nums.first() {
Some(n) => println!("first is {n}"),
None => println!("empty"),
}
println!("{a}");
}The reverse mistake also happens. A function declared -> Option<i32> or -> Result<i32, E> that ends in a bare 42 reports expected Option<i32>, found integer. Wrap the value as Some(42) or Ok(42).
Inside a function that returns Result, the ? operator unwraps an Ok and returns early on an Err. It replaces many manual matches:
use std::num::ParseIntError;
fn parse_and_double(s: &str) -> Result<i32, ParseIntError> {
let n: i32 = s.trim().parse()?;
Ok(n * 2)
}
fn main() {
println!("{:?}", parse_and_double(" 21 "));
println!("{:?}", parse_and_double("abc"));
}Case 5: branches that disagree
All branches of an if/else or a match must have the same type, because the whole construct is a single expression with a single type.
fn main() {
let n = 5;
let label = if n > 0 { "positive" } else { 0 };
println!("{label}");
}The error is E0308: if and else have incompatible types. The labels show one branch as &str and the other as an integer. Decide on one type for the result and make every branch produce it:
fn main() {
let n = 5;
let label = if n > 0 { "positive" } else { "zero or negative" };
println!("{label}");
}The same applies to match arms. A common cause is one arm that ends in a semicolon and so has type () while the others return a value. Check each arm's final line.
An arm that never returns, such as panic!(), return, break, or continue, has type ! (the never type). It fits with any other type, which is why None => return works next to an arm that produces a value.
Case 6: your annotation is the problem
Sometimes the expression is right and the declared type is wrong. If you wrote let count: usize = -1;, no conversion helps, because a usize cannot be negative. In that case, change the annotation to i32 or isize.
Before you add a conversion, ask whether the type you declared is the type you intended.
Common mistakes
- Adding
.unwrap()to silence anOptionerror. The program then panics at run time when the value isNone. Useunwrap_or,match,if let, or?when the failure case is realistic. - Using
asfor every number conversion. It never fails to compile, and it can corrupt values quietly. - Calling
.to_string()or.clone()to satisfy the type checker. This can hide that a function should take a borrow. - Fixing the found type when the expected type came from a wrong function signature. Follow the "expected due to this" label to see where the expectation originated.
Exercise
This function should return the length of the first word, or 0 for an empty string. Find the E0308 errors and fix them. fn firstwordlen(s: &str) -> usize { let word = s.split_whitespace().next(); word.len(); }
Show answer
There are two problems. First, next() returns Option<&str>, so word.len() is called on an Option and does not compile. Unwrap it with a default, for example s.split_whitespace().next().unwrap_or(""). Second, the trailing semicolon after word.len() makes the body evaluate to (), and rustc reports expected usize, found ()``. Remove the semicolon. A fixed version:
fn firstwordlen(s: &str) -> usize {
let word = s.splitwhitespace().next().unwrapor("");
word.len()
}
Exercise
What are two ways to fix let id: u64 = user_id; when user_id is a u32, and when would you choose u64::try_from instead of u64::from on a different pair of types?
Show answer
Write let id: u64 = u64::from(user_id); or let id: u64 = user_id.into();. Both are lossless and checked at compile time. Use try_from when the conversion can fail for some values, such as u8::try_from(wide) where wide is a u32, or converting a signed value to an unsigned one. It returns a Result, so you handle the out-of-range case.