Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readRust
#rust#e0308#types#compiler-errors
Bold white headline reading TYPE MISMATCH with a Rust crate holding two amber blocks that do not fit on the right.

Introduction & Quick Summary

The compiler points at two pieces of code and names their types:

code
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 this

E0308 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:

  • String where &str is 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 in Ok(value) of the wrong shape, or a plain value.
  • if/match arms returning different types, including () from an else that does not exist.
  • A closure passed to map returning a reference when an owned value is needed.
  • ? on a Result whose error type has no From conversion 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:

rust
// 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:

rust
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:

ExpectedFoundConversionCost
&strString&s or s.as_str()none, borrows
String&strs.to_string() or s.to_owned()allocates
u16Strings.parse::<u16>()?parses, may fail
i64i32i64::from(x)widening only, infallible
i32i64i32::try_from(x)?narrowing, fallible
Option<T>TSome(x) or .ok_or(err)?none
Box<dyn Error>MyErrorBox::new(e) or impl From<MyError>boxing or custom impl
Vec<u8>&[u8]v.as_slice() or &vnone

Key Comparison Table

Telling the type errors apart, since the fixes differ:

CodeMessageMeaningFix
E0308mismatched typesexpression type differs from contextadd a conversion
E0277trait bound not satisfiedno From/Display/Clone implimplement or convert
E0369binary operation cannot be applied+ between incompatible typesconvert one side
E0061wrong number of argumentssignature mismatchread the signature
E0599no method namedmethod missing for this typeimport the trait
E0282type annotations neededinference has no constraintannotate or turbofish

Where the mismatch usually comes from in real code:

ContextTypical messageUsual fix
let x: T = exprexpected T, found Uconvert expr
function argumentexpected &str, found Stringpass &value
tail expressionexpected Result<T, E>, found Twrap in Ok(T)
if without elseexpected T, found ()add else or return ()
match armsexpected T, found U in arm 2unify arm types
closure in mapexpected T, found &Tuse 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:

rust
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 ()

rust
let label = if count > 0 { "some" }; // E0308: expected (), found &str

The 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:

rust
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:

rust
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:

rust
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); // infallible

as 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

rust
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 String

names.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 documentation

The Rust documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.