/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
cat > main.rs <<'EOF'
fn main() {
let port: u16 = "8080";
println!("{port}");
}
EOF
rustc main.rsOutput · 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
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 && ./mainOutput
8080 hello Ada 42
Common shapes of E0308
| expected | found | Fix |
|---|---|---|
| u16 / i32 / f64 | &str | "8080".parse::<u16>() |
| &str | String | pass &s or s.as_str() |
| String | &str | "text".to_string() or String::from("text") |
| i32 (function return) | () | remove the semicolon after the last expression |
| i64 | i32 | value.into() or i64::from(value) |
| Option<T> | T | wrap with Some(value) |
Sources
Related pages
errors · rustRust error[E0382]: borrow of moved valuerustc reports E0382 when a variable is used after its value moved to another binding or function. Borrow it with &, clone it, or reorder the code. Real output.compare · rustRust String vs &str: what is the difference?String is an owned, growable, heap-allocated UTF-8 buffer; &str is a borrowed view into UTF-8 bytes. What to store, what to take as a parameter, conversions.flags · cargocargo build --release: optimised builds and target/releasecargo build --release uses the release profile (opt-level 3, no overflow checks) and writes to target/release. Debug vs release, and how to tune the profile.