FAQ - Help and questions

How do I fix error E0308, "mismatched types"?

#errors#compiler#typespublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

E0308 means the compiler found one type where it needs another. Compare the expected and found types in the message. A very common cause is a semicolon after the last expression of a function, which turns its value into the empty type (). Remove it, or convert the value to the type needed.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Rust never converts between types silently (an i32 is not a u64, a &str is not a String), so every place that expects a type checks it. The message always has two parts: what was expected and what was found. Read those first.

How to do it#

  1. Look at this function. It promises an i32, but ends in x * 2;.
src/main.rsrust
fn double(x: i32) -> i32 {
    x * 2;
}

fn main() {
    println!("{}", double(4));
}
text
error[E0308]: mismatched types
 --> src/main.rs:1:22
  |
1 | fn double(x: i32) -> i32 {
  |    ------            ^^^ expected `i32`, found `()`
  |    |
  |    implicitly returns `()` as its body has no tail or `return` expression
2 |     x * 2;
  |          - help: remove this semicolon to return this value

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0308`.
  1. The semicolon turns the last line into a statement, so the function body has no value and its type is (). Remove the semicolon.
src/main.rsrust
fn double(x: i32) -> i32 {
    x * 2
}

fn main() {
    println!("{}", double(4));
}
text
8

Other common causes and fixes#

  • expected String, found &str: call .to_string() or String::from(...).
  • expected u64, found u32 (or any two number types): convert on purpose with value as u64 or u64::from(value); from is only offered where no information can be lost.
  • expected Option<T>, found T: wrap the value in Some(...).
  • if and else branches (or match arms) that produce different types: make them agree.

Common mistakes#

  • Fixing the symptom with as where the types differ for a reason, for example casting a possibly negative i32 to usize. A negative value turns into a huge number.
  • Adding return to every line instead of understanding that the last expression without a semicolon is the value.

Run rustc --explain E0308 for the long explanation with more examples.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet