Skip to content

/errors/rust/e0308-mismatched-types

Rust error[E0308]: mismatched types

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · rustc 1.98.1 (48a229cea 2026-09-01)updated
tool
Rust
exit code
1
versions
Rust 1.x
os
any

error[E0308]: mismatched types means rustc expected one type and found another. The message shows both: expected u16, found &str, with a second label pointing at the code that caused the expectation (a type annotation, a function signature or a return type). Rust never converts implicitly: parse the string, borrow or clone the value, or change the annotation.

Reproduce it

bash
cat > main.rs <<'EOF'
fn main() {
    let port: u16 = "8080";
    println!("{port}");
}
EOF
rustc main.rs

Output · exit 1

error[E0308]: mismatched types
 --> main.rs:2:21
  |
2 |     let port: u16 = "8080";
  |               ---   ^^^^^^ expected `u16`, found `&str`
  |               |
  |               expected due to this

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0308`.

Fix: convert explicitly

bash
cat > main.rs <<'EOF'
fn greet(name: &str) -> String {
    format!("hello {name}")          // no semicolon: this is the return value
}

fn main() {
    let port: u16 = "8080".parse().expect("valid port number");
    let owned = String::from("Ada");
    println!("{port}");
    println!("{}", greet(&owned));   // &String coerces to &str
    let n: i64 = 42_i32.into();      // lossless integer widening
    println!("{n}");
}
EOF
rustc main.rs && ./main

Output

8080
hello Ada
42

Common shapes of E0308

expectedfoundFix
u16 / i32 / f64&str"8080".parse::<u16>()
&strStringpass &s or s.as_str()
String&str"text".to_string() or String::from("text")
i32 (function return)()remove the semicolon after the last expression
i64i32value.into() or i64::from(value)
Option<T>Twrap with Some(value)

Sources