Looking for a structured path? Browse all Rust lessons.
- Maintained by
- Learning Platform content team
- Reviewed by
- Learning Platform source and executable-example contract
Fix Rust E0308: mismatched types
The problem: E0308 means an expression produced one type where the surrounding code requires another. The message always has two halves: expected is what the context demands (a return type, a parameter, a let annotation, the other arm of an if), and found is what you actually wrote. Fix the side that is wrong; Rust never converts between them silently.
Reproduce the error
fn total_cents(items: &[u32]) -> u32 {
let mut sum = 0;
for item in items {
sum += item;
}
sum;
}
fn main() {
println!("{}", total_cents(&[250, 199]));
}
The compiler reports expected u32, found (). In Rust, the last expression of a block is its value. The semicolon after sum turns it into a statement, so the function body ends with the unit value () instead of a u32. The diagnostic usually points at the semicolon and suggests removing it.
Preferred fix: let the final expression be the value
fn total_cents(items: &[u32]) -> u32 {
let mut sum = 0;
for item in items {
sum += item;
}
sum
}
fn main() {
println!("{}", total_cents(&[250, 199]));
}
Expected output:
449
sum without a semicolon is the tail expression, so the block evaluates to u32 and matches the declared return type. return sum; also works and is common for early exits.
Other valid fixes
A Result where a value is expected. "8080".parse::<u16>() returns Result<u16, ParseIntError>, not u16. Handle the error case with ?, match, or unwrap_or, depending on whether the caller should see the failure:
use std::num::ParseIntError;
fn parse_port(input: &str) -> Result<u16, ParseIntError> {
let port = input.trim().parse::<u16>()?;
Ok(port)
}
fn main() {
match parse_port(" 8080 ") {
Ok(port) => println!("port {port}"),
Err(error) => println!("invalid: {error}"),
}
let port = parse_port("not-a-port").unwrap_or(3000);
println!("fallback {port}");
}
String versus &str. A &str literal passed where a String is required needs .to_string() or String::from. In the other direction, borrow with &name, which converts &String to &str automatically.
Integer widths. u8, i32, and u64 are distinct types. Widen with u64::from(value), which cannot lose data, or use TryFrom when narrowing.
Common failure mode: reaching for as
as makes the types line up, but on integers it truncates without warning: 300_i32 as u8 is 44. Use it only when wrapping is the behavior you want. u8::try_from(300) returns an Err you can handle instead.
Paste the failing version into the Rust playground and remove the semicolon to see the error disappear. Review tail expressions in the functions lesson, then learn to handle Result values in Option and Result. For ownership errors, see our E0382 guide.