Rust E0308: mismatched types
E0308 is a missing conversion: String versus &str, integer widths, branch types, or an unwrapped tail. Match expected and found types before editing code.

Introduction & Quick Summary
The compiler points at two pieces of code and names their types:
error[E0308]: mismatched types
--> src/main.rs:6:20
|
6 | let port: u16 = std::env::var("PORT").unwrap();
| --- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u16`, found `String`
| |
| expected due to thisE0308 is the most common Rust error: an expression produces a type the surrounding context does not accept. Unlike a borrow error, nothing subtle is happening — a conversion is missing, a value is wrapped differently, or two branches of the same construct disagree.
Where it appears:
Stringwhere&stris expected, or the reverse, in function arguments and struct fields.- Integer literals and parsed strings assigned to a narrower type (
u16,usize,i64). - A function that returns
Result<T, E>but whose body ends inOk(value)of the wrong shape, or a plainvalue. if/matcharms returning different types, including()from anelsethat does not exist.- A closure passed to
mapreturning a reference when an owned value is needed. ?on aResultwhose error type has noFromconversion into the function's error type — usually E0277, but often reported alongside E0308 when the tail expression is involved.
Quick answer: convert explicitly at the boundary — .as_str() to borrow, .to_string() or .to_owned() to own, parse::<T>() with ? for text to number, i64::from(x) or u16::try_from(x) for widths — and make both branches of an if or match produce the same type.
Core Mechanics, Signatures & Reproducible Setup
Rust has no implicit conversions between user-facing types. Coercions exist for references (&String to &str, &T to &dyn Trait), for array to slice, and for Box<T> in some positions, but never for String to &str by value or for i64 to i32. E0308 is the compiler refusing one of the conversions you assumed.
Reproduce it and fix it in one file:
// src/main.rs
use std::env;
fn port_from_env() -> Result<u16, Box<dyn std::error::Error>> {
let raw = env::var("PORT")?; // String
let port: u16 = raw; // E0308: expected u16, found String
Ok(port)
}
fn main() {
println!("{:?}", port_from_env());
}The fixed version parses and keeps the error path intact:
fn port_from_env() -> Result<u16, Box<dyn std::error::Error>> {
let raw = env::var("PORT")?;
let port: u16 = raw.parse()?; // ParseIntError converts into Box<dyn Error>
Ok(port)
}parse() needs a target type; the annotation on port supplies it. Without one the compiler reports type annotations needed instead, which is a different and equally common message.
The conversions that resolve most E0308 reports:
| Expected | Found | Conversion | Cost |
|---|---|---|---|
&str | String | &s or s.as_str() | none, borrows |
String | &str | s.to_string() or s.to_owned() | allocates |
u16 | String | s.parse::<u16>()? | parses, may fail |
i64 | i32 | i64::from(x) | widening only, infallible |
i32 | i64 | i32::try_from(x)? | narrowing, fallible |
Option<T> | T | Some(x) or .ok_or(err)? | none |
Box<dyn Error> | MyError | Box::new(e) or impl From<MyError> | boxing or custom impl |
Vec<u8> | &[u8] | v.as_slice() or &v | none |
Key Comparison Table
Telling the type errors apart, since the fixes differ:
| Code | Message | Meaning | Fix |
|---|---|---|---|
| E0308 | mismatched types | expression type differs from context | add a conversion |
| E0277 | trait bound not satisfied | no From/Display/Clone impl | implement or convert |
| E0369 | binary operation cannot be applied | + between incompatible types | convert one side |
| E0061 | wrong number of arguments | signature mismatch | read the signature |
| E0599 | no method named | method missing for this type | import the trait |
| E0282 | type annotations needed | inference has no constraint | annotate or turbofish |
Where the mismatch usually comes from in real code:
| Context | Typical message | Usual fix |
|---|---|---|
let x: T = expr | expected T, found U | convert expr |
| function argument | expected &str, found String | pass &value |
| tail expression | expected Result<T, E>, found T | wrap in Ok(T) |
if without else | expected T, found () | add else or return () |
match arms | expected T, found U in arm 2 | unify arm types |
closure in map | expected T, found &T | use into_iter or clone |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. String versus &str in structs and functions
A struct field of type String cannot be initialised from a &'static str without conversion, and a String cannot be passed where &str is expected:
struct Config {
name: String,
path: &'static str, // only literal or leaked strings can go here
}
fn greet(name: &str) -> String {
format!("hello {name}")
}
let owned = String::from("api");
greet(&owned); // deref coercion: &String -> &str
let cfg = Config { name: owned, path: "/etc/app" };If the field must own a runtime string, use String; if it must borrow, add a lifetime parameter. Reaching for &'static str to avoid the lifetime is what produces expected &str, found String in a constructor.
2. if without else returns ()
let label = if count > 0 { "some" }; // E0308: expected (), found &strThe missing branch makes the expression type () while the present branch produces &str. Either add the other branch or add a semicolon to discard the value:
let label = if count > 0 { "some" } else { "none" };The same rule applies to match: every arm must produce one type, and an arm that ends with a statement instead of an expression silently produces ().
3. Tail expressions and Ok(...)
A function declared to return Result<T, E> requires the last expression to be a Result:
fn load() -> Result<String, std::io::Error> {
let text = std::fs::read_to_string("config.toml")?;
text // E0308: expected Result<String, Error>, found String
}
fn load_fixed() -> Result<String, std::io::Error> {
let text = std::fs::read_to_string("config.toml")?;
Ok(text)
}Because ? already unwraps, the value after it is plain T. Wrapping the tail in Ok(...) is the whole fix; the error message names the exact line, which is what makes this case fast to spot.
4. Numeric widths without silent truncation
Rust never converts integers implicitly, and the useful conversion depends on direction:
let big: i64 = 4_000_000_000;
let small: i32 = big as i32; // compiles, wraps silently
let checked: i32 = i32::try_from(big)?; // returns Err on overflow
let n: u8 = 200;
let widened: u32 = u32::from(n); // infallibleas is a lossy cast and the compiler will not warn; try_from is what turns a potential data bug into an error. For parsing user input, .parse::<u16>() returns Result and rejects 65536 correctly, while as would wrap it to 0.
5. Closures and iterator adapters that change ownership
let names: Vec<String> = vec!["a".into(), "b".into()];
let upper: Vec<String> = names.iter().map(|n| n.to_uppercase()).collect(); // ok
let upper2: Vec<String> = names.iter().map(|n| n).collect(); // E0308: &String vs Stringnames.iter() yields &String, so a closure returning n yields a reference and collect::<Vec<String>>() rejects it. Use into_iter() to consume, or .cloned() / .map(|n| n.clone()) to own. The error message names the collect call, not the closure, so read the "expected/found" pair before editing the wrong line.
Common Compilation/Runtime Mistakes & Version Gotchas
Adding as everywhere. Casting silences E0308 and introduces silent truncation, sign flips, and float rounding. Prefer From/Into for widening, TryFrom for narrowing, and as only where the loss is deliberate and documented.
Cloning to satisfy the borrow checker when the type is the problem. s.clone() fixes expected String, found &String, and does not fix expected u16, found String. Match the conversion to the type pair in the message.
Ignoring the "expected due to this" note. The note points at the annotation or signature that constrains the type, which is often not where the value was created. Changing the annotation to u16 moves the error to the env::var line; parsing moves the fix to the right place.
Version differences worth knowing. Rust 2024 changed closure capture to be more precise, so code that compiled under edition 2021 can now produce E0308 where a closure captured a whole struct instead of one field. Rust 1.90 made rust-lld the default linker on some targets, which produces linker errors rather than type errors but arrives in the same upgrade. impl Trait in return position now allows more inference than older releases, so a function that needed an explicit Box<dyn Trait> may accept the concrete type — and code written for 1.60 may fail to compile unmodified against a newer clippy lint set.
Comparing the two versions of a failing line. When a refactor changes types, diff the file against the last working revision with Diff and inspect the serde-derived structures with the JSON viewer to confirm the field types the compiler sees.
Reference material: Rust error index E0308 and The Rust Book, data types.
Official references
primary documentationThe Rust documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust E0061: this function takes 1 argument but 2 were supplied
E0061 counts arguments at the call site. Check the signature, method versus associated function, generic defaults, and trait impls that changed arity.
Rust E0282: type annotations needed
E0282 means inference ran out of information. Annotate the binding, add a turbofish to collect or parse, or fix the signature the value flows into.
Rust E0463: can't find crate for std
The target triple has no standard library installed. Add the target with rustup, check the target string and link the right ABI.
Rust E0432: unresolved import
E0432 is a module graph problem: a missing mod declaration, a private parent or a wrong path. Fix the tree, not the dependency list.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.