Rust

Fix Rust E0308 "mismatched types" — Convert the Value, Fix the Signature, or Give Both Sides One Type

Two sides of one expression wanted different types, and Rust refused to guess which one should change. This guide separates the ways the two sides come to disagree — an argument, a return value, two branches, a string and a slice, a value and a reference, a value and the unit a stray semicolon left behind — and matches each one to its repair: restate the type where it is declared, convert the value with the conversion that cannot lose it, try the conversion that can, and cast only when the loss is the design.

Written November 22, 2026 · Tested with Rust 1.99.0 · 44 min read

By the end of this guide
  • The rule underneath: Rust does not convert numbers, strings, or values for you
  • The first failure: the argument and the return — one signature, two directions
  • The second failure: branches that disagree — if, else, and match
  • The third failure: String and &str — ownership is part of the type

Written November 22, 2026

Tested with Rust 1.99.0

What this guide is

Error E0308 has one sentence at its center: expected type did not match the received type. That is the wording of the error codes index, and every part of it carries diagnostic weight. There is an expected type — named by a function signature, a return declaration, a type annotation, or the other arm of a branch. There is a received type — the type the expression actually produced. And there is a place where the two met — an argument, an assignment, a return position, a condition — and the compiler refused at that meeting point rather than converting one side into the other in silence.

That refusal is the whole repair. E0308 is never really about the value being wrong in itself; an i32 is a perfectly good value, a string literal is a perfectly good string. The error is about a disagreement between two places in the program, and the fix is decided by asking which side owns the truth. Sometimes the signature is the design and the value must be converted to meet it. Sometimes the value is the design and the signature or the annotation is the stale side that should change. Sometimes neither side is wrong and the program is missing the conversion step that relates them — a borrow, a dereference, a From conversion, a fallible TryFrom, or, as the last resort with the loss priced in, an as cast.

This guide works through the error in the order that separates its causes: the rule underneath — Rust converts almost nothing implicitly, and the short list of what it does convert is worth knowing exactly — then the failures one family at a time: the argument and return forms, the branch forms where two arms or a missing arm disagree, the string forms, the reference forms, and the unit form, where a single semicolon turns a value into (). Then the fixes, in reach order, the traps, a decision table, and a checklist.

Build every program in this guide with rustc --edition 2021. In the compiler transcripts below, the full file path in the location line is shortened to the file name; every other character is exactly as the compiler printed it.

The rule underneath: Rust does not convert numbers, strings, or values for you

Rust is a statically typed language: the compiler must know the type of every value at compile time, and a variable has a single type. The error codes index states the consequence directly: this error occurs when an expression was used in a place where the compiler expected an expression of a different type, most commonly when calling a function and passing an argument of a different type than the declaration. What the index leaves implicit is the part that surprises programmers arriving from languages with implicit numeric promotion: Rust performs no automatic conversion between numeric types at all. An i32 is not an i64 waiting to be widened; a u32 is not an i32 with a different mood; a float is not an integer rounded by good intentions. Each integer type in the standard table — i8 through i128, u8 through u128, isize and usize — is a distinct type, and a place that expects one of them rejects all the others with E0308 until the program states a conversion.

The smallest demonstration passes a variable of one integer type to a function that takes another:

Rust
fn total(x: i64) -> i64 { x + 1 }
fn main() {
    let n: i32 = 5;
    let t = total(n);
    println!("t = {t}");
}
Terminal
$ rustc --edition 2021 fail_canonical.rs -o fail_canonical
error[E0308]: mismatched types
 --> fail_canonical.rs:4:19
  |
4 |     let t = total(n);
  |             ----- ^ expected `i64`, found `i32`
  |             |
  |             arguments to this function are incorrect
  |
note: function defined here
 --> fail_canonical.rs:1:4
  |
1 | fn total(x: i64) -> i64 { x + 1 }
  |    ^^^^^ ------
help: you can convert an `i32` to an `i64`
  |
4 |     let t = total(n.into());
  |                    +++++++

error: aborting due to 1 previous error

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

Read the diagnostic's three positions, because they recur in every form of this error. The first line names the meeting point and the two types: expected i64, found i32. The note points at the function definition, because the signature is where the expectation was set — the compiler is showing you both parties to the disagreement, not just the line that failed. And the help proposes a conversion, .into(), which works here because converting an i32 to an i64 cannot lose any value, so the standard library provides it. Not every E0308 help can offer that; the sections below include mismatches where no lossless conversion exists and the help necessarily falls silent or points somewhere else.

The literal exception: an untyped literal is not yet a type

One refinement prevents a common confusion when reproducing this error. The program above fails because n was declared with an explicit i32 annotation, which fixed its type before the call. A bare integer literal in the same call does not fail:

Rust
fn takes_i64(x: i64) -> i64 { x }
fn takes_u8(x: u8) -> u8 { x }
fn main() {
    println!("a = {}", takes_i64(5));
    println!("b = {}", takes_u8(5));
    let x = 5;
    println!("x = {x}");
}
Terminal
$ rustc --edition 2021 ok_literal_adapts.rs -o ok_literal_adapts
$ ./ok_literal_adapts
a = 5
b = 5
x = 5

The literal 5 has no fixed type until the context gives it one: passed to a function taking i64, it is an i64; passed to a function taking u8, it is a u8; bound with no annotation and no other pressure, it defaults to i32, which is Rust's default integer type. Literal adaptation is inference, not conversion — the literal was never an i32 that got widened; it was an integer literal that took the type the meeting point required. This is why E0308 so often appears only after code is refactored: an inline literal that compiled for months becomes a named variable with an annotation, or gets returned from another function with its own signature, and the type that inference used to supply for free is now fixed on the wrong side of the call. When a mismatch involves a literal, the fix is usually a suffix or an annotation — 5i64, let b: i64 = 5; — covered with the other annotation repairs in the fixes. When it involves a variable, no suffix exists; the value must be converted or its declaration must change.

What Rust does convert automatically: coercions, and only coercions

There is a narrow, precisely defined set of implicit conversions, called coercions, and knowing its boundary is what separates reading E0308 well from guessing at it. The Reference defines coercions as implicit operations that change the type of a value, occurring automatically at specific locations — coercion sites — and highly restricted in what types actually coerce. The sites include let statements with an explicit type, function arguments, struct field values, function results, and assigned values. The conversions themselves are mostly about references and pointers, not values: a &mut T coerces to a &T; a reference coerces through Deref to a reference of the target type, which is why a &String can serve where a &str is expected and a &Vec<T> where a &[T] is expected; an array reference coerces to a slice; a function item coerces to a function pointer. The fixes section runs a program that leans on three of these at once.

Hold the two halves together and the rule is one sentence: at a meeting point, Rust will adjust how a value is accessed — mutability of a borrow, the view a dereference provides, the unsizing of an array into a slice — but it will never change what a value is: not its width, not its signedness, not its ownership, not number into string or string into number. Every E0308 in this guide is a place where the program needed the second kind of change and had not written it. The fixes are the spellings for writing it.

The first failure: the argument and the return — one signature, two directions

The canonical form above is the argument direction: the caller's value disagrees with the callee's parameter. The same disagreement in the other direction — the function's own body disagrees with its own return declaration — produces the same error with the meeting point inside the function:

Rust
fn count() -> i64 {
    let n: i32 = 5;
    n
}
fn main() {
    println!("count = {}", count());
}
Terminal
$ rustc --edition 2021 fail_return_type.rs -o fail_return_type
error[E0308]: mismatched types
 --> fail_return_type.rs:3:5
  |
1 | fn count() -> i64 {
  |               --- expected `i64` because of return type
2 |     let n: i32 = 5;
3 |     n
  |     ^ expected `i64`, found `i32`
  |
help: you can convert an `i32` to an `i64`
  |
3 |     n.into()
  |      +++++++

error: aborting due to 1 previous error

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

Nothing here is a call-site problem. The return declaration -> i64 set the expectation, the local annotation : i32 set the received type, and the final expression is where they met. The repair question is the same one the argument form asks, sharpened: which annotation is the design? If the function's contract is genuinely 64-bit — callers store the result in i64 fields, the value can grow past 32 bits — the local variable is the side to convert or redeclare. If the count can never leave the 32-bit range and the return type was written wide out of habit, the signature is the side to change, and every caller benefits from the narrower truth. E0308 does not know which; it only knows the two sides disagree. The programmer's job in every form of this error is supplying that judgment, and the rest of the diagnostic — which side the note points at, which conversion the help offers — is evidence for it.

A third member of this family swaps signedness instead of width, and it is the one with real consequences hiding inside it:

Rust
fn takes_u32(x: u32) -> u32 { x }
fn main() {
    let n: i32 = -5;
    let y = takes_u32(n);
    println!("y = {y}");
}
Terminal
$ rustc --edition 2021 fail_annotation_arg.rs -o fail_annotation_arg
error[E0308]: mismatched types
 --> fail_annotation_arg.rs:4:23
  |
4 |     let y = takes_u32(n);
  |             --------- ^ expected `u32`, found `i32`
  |             |
  |             arguments to this function are incorrect
  |
note: function defined here
 --> fail_annotation_arg.rs:1:4
  |
1 | fn takes_u32(x: u32) -> u32 { x }
  |    ^^^^^^^^^ ------
help: you can convert an `i32` to a `u32` and panic if the converted value doesn't fit
  |
4 |     let y = takes_u32(n.try_into().unwrap());
  |                        ++++++++++++++++++++

error: aborting due to 1 previous error

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

An i32 holding -5 cannot meet a u32 parameter, and the reason is deeper than width: the received value is not merely stored differently, it is unrepresentable. No From conversion exists for this pair either, for the same reason none exists from i64 down to i32 — the From trait is reserved for conversions that cannot fail and cannot lose. Signed-to-unsigned and wide-to-narrow conversions are the natural home of TryFrom, covered as a fix below, and of the design question that should come first: a count that can be negative and a count that cannot are different domains, and the mismatch is the type system asking the program to say which domain it is in.

The second failure: branches that disagree — if, else, and match

An if expression used as a value is a meeting point of its own arms. The Book's control-flow chapter states the rule plainly: the values that have the potential to be results from each arm of the if must be the same type, because the variable the expression binds must have a single type, known definitively at compile time. When the arms disagree, the error names the whole construct:

Rust
fn main() {
    let condition = true;
    let number = if condition { 5 } else { "six" };
    println!("number = {number}");
}
Terminal
$ rustc --edition 2021 fail_if_else.rs -o fail_if_else
error[E0308]: `if` and `else` have incompatible types
 --> fail_if_else.rs:3:44
  |
3 |     let number = if condition { 5 } else { "six" };
  |                                 -          ^^^^^ expected integer, found `&str`
  |                                 |
  |                                 expected because of this

error: aborting due to 1 previous error

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

The diagnostic underlines the second arm, notes that the first arm set the expectation, and reports the pair as integer and &str. There is no conversion to reach for first here, because the disagreement is not between a value and a signature — it is between two intentions. One arm believes the result is a number; the other believes it is text. The program must decide what number is: if it is a number, the text arm is a bug in that branch; if it is display text, both arms should be text, with the numeric arm converted by formatting; if the two arms genuinely produce different kinds of thing, the result type is an enum or an Option away from being honest, and no cast in the fixes section will substitute for that decision.

match expressions follow the same rule across all of their arms, through the same mechanism — the compiler must find one common type that every arm's value can be:

Rust
fn main() {
    let code = 2;
    let label = match code {
        1 => "one",
        2 => 2,
        _ => "other",
    };
    println!("label = {label}");
}
Terminal
$ rustc --edition 2021 fail_match_arms.rs -o fail_match_arms
error[E0308]: `match` arms have incompatible types
 --> fail_match_arms.rs:5:14
  |
3 |       let label = match code {
  |  _________________-
4 | |         1 => "one",
  | |              ----- this is found to be of type `&str`
5 | |         2 => 2,
  | |              ^ expected `&str`, found integer
6 | |         _ => "other",
7 | |     };
  | |_____- `match` arms have incompatible types

error: aborting due to 1 previous error

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

The repair discipline is identical: read which arm set the expectation and which arm broke it, then decide the result type once and bring every arm to it. Branch mismatches are the form of E0308 where converting the underlined value is most often the wrong first move, because the underlined arm is as likely to be the honest one as the arm that set the expectation.

The unit arm: a branch that produces nothing is a type too

The subtlest branch form replaces one arm's value with nothing at all. An empty block evaluates to the unit type, written (), and unit is a real type with a real place in this error:

Rust
fn main() {
    let condition = true;
    let number = if condition { 5 } else { };
    println!("number = {number}");
}
Terminal
$ rustc --edition 2021 fail_if_else_unit.rs -o fail_if_else_unit
error[E0308]: `if` and `else` have incompatible types
 --> fail_if_else_unit.rs:3:42
  |
3 |     let number = if condition { 5 } else { };
  |                                 -        ^^^ expected integer, found `()`
  |                                 |
  |                                 expected because of this

error: aborting due to 1 previous error

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

Expected integer, found () — the else arm did not produce a wrong value; it produced no value, and no value is itself a type that mismatches every other type. This form appears in real code when an arm is stubbed out during editing, when a function's last expression is placed inside one branch only, or when an arm ends in a macro or a statement that yields unit where the other arm yields data. The fix is to give the empty arm the value it owes the expression — a default, an error string, a computed fallback — or, if the branch was never meant to produce a value at all, to stop using the if as an expression: perform the side effect inside the branch and bind nothing.

That last distinction has its own error code, and meeting it once, labeled correctly, prevents a long confusion. An if with no else at all, used where a value is required, is not reported as E0308:

Rust
fn main() {
    let condition = true;
    let number = if condition { 5 };
    println!("number = {number}");
}
Terminal
$ rustc --edition 2021 fail_if_no_else.rs -o fail_if_no_else
error[E0317]: `if` may be missing an `else` clause
 --> fail_if_no_else.rs:3:18
  |
3 |     let number = if condition { 5 };
  |                  ^^^^^^^^^^^^^^^-^^
  |                  |              |
  |                  |              found here
  |                  expected integer, found `()`
  |
  = note: `if` expressions without `else` evaluate to `()`
  = help: consider adding an `else` block that evaluates to the expected type

error: aborting due to 1 previous error

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

The code is E0317, not E0308, and its note carries the fact that explains both errors: if expressions without else evaluate to (). The compiler separates the cases because the repairs differ in kind — E0308 with a unit arm means an arm exists and owes a value; E0317 means the arm that would owe the fallback value was never written, and the help says so, proposing an else block of the expected type. The same E0317 appears when the value-producing if without else sits in a function's return position. Read the code in the first line of any branch diagnostic before reaching for this guide's conversion fixes: the branch family splits at exactly this line.

The third failure: String and &str — ownership is part of the type

The string family of E0308 is the one new Rust programmers meet most, because Rust has two common string types where many languages have one, and they differ in ownership, not in spelling. A String is an owned, growable buffer of UTF-8 text. A &str is a borrowed view into text owned elsewhere — a string literal is a &'static str, a view into the program's own data. A function that takes a String is claiming ownership of a buffer it may keep, grow, or drop; a string literal has no buffer to give. The meeting fails:

Rust
fn greet(name: String) {
    println!("hello, {name}");
}
fn main() {
    greet("Ada");
}
Terminal
$ rustc --edition 2021 fail_string_param.rs -o fail_string_param
error[E0308]: mismatched types
 --> fail_string_param.rs:5:11
  |
5 |     greet("Ada");
  |     ----- ^^^^^ expected `String`, found `&str`
  |     |
  |     arguments to this function are incorrect
  |
note: function defined here
 --> fail_string_param.rs:1:4
  |
1 | fn greet(name: String) {
  |    ^^^^^ ------------
help: try using a conversion method
  |
5 |     greet("Ada".to_string());
  |                ++++++++++++

error: aborting due to 1 previous error

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

The help proposes the conversion the fixes section prices properly: .to_string(), which allocates a new owned buffer holding a copy of the literal's text. The same disagreement in annotation form is identical in structure — the expected side is set by the annotation, the received side is the literal's type:

Rust
fn main() {
    let s: String = "hello";
    println!("s = {s}");
}
Terminal
$ rustc --edition 2021 fail_string_assign.rs -o fail_string_assign
error[E0308]: mismatched types
 --> fail_string_assign.rs:2:21
  |
2 |     let s: String = "hello";
  |            ------   ^^^^^^^ expected `String`, found `&str`
  |            |
  |            expected due to this
  |
help: try using a conversion method
  |
2 |     let s: String = "hello".to_string();
  |                            ++++++++++++

error: aborting due to 1 previous error

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

The reverse direction is the instructive one, because it does not fail. A function taking &str accepts a &String argument without any conversion written at the call, because the coercion rules from the second section apply: at the argument site, a &String coerces through Deref to the &str view of the same text. The fix_string.rs program in the fixes section calls a &str function with both a borrowed owned string and a literal, and both calls compile. This asymmetry is the design lesson of the whole family: a signature asking for &str is asking for less — a look at some text, wherever it lives — and therefore accepts strictly more callers than a signature asking for String. When the string form of E0308 lands on your code, the first question is not how to convert the argument; it is whether the parameter needed to own text at all. A function that only reads its string argument, formats it, compares it, or passes it onward as a view should take &str, and changing that one signature removes the error for every present and future caller at once. A function that stores the text, extends it, or returns it as part of a larger owned structure genuinely needs String, and then the conversion belongs at the call sites, priced as an allocation per call.

The fourth failure: a value where a reference belongs, and the reverse

References are types too, and the difference between T and &T is a type difference like any other in this guide. Passing a value where a reference is expected fails:

Rust
fn show(x: &i32) {
    println!("x = {x}");
}
fn main() {
    let n = 5;
    show(n);
}
Terminal
$ rustc --edition 2021 fail_ref_value.rs -o fail_ref_value
error[E0308]: mismatched types
 --> fail_ref_value.rs:6:10
  |
6 |     show(n);
  |     ---- ^ expected `&i32`, found integer
  |     |
  |     arguments to this function are incorrect
  |
note: function defined here
 --> fail_ref_value.rs:1:4
  |
1 | fn show(x: &i32) {
  |    ^^^^ -------
help: consider borrowing here
  |
6 |     show(&n);
  |          +

error: aborting due to 1 previous error

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

The help is one character: borrow at the call. The reverse direction fails as well, and its repair is the mirror operation:

Rust
fn show(x: i32) {
    println!("x = {x}");
}
fn main() {
    let n = 5;
    show(&n);
}
Terminal
$ rustc --edition 2021 fail_value_ref.rs -o fail_value_ref
error[E0308]: mismatched types
 --> fail_value_ref.rs:6:10
  |
6 |     show(&n);
  |     ---- ^^ expected `i32`, found `&{integer}`
  |     |
  |     arguments to this function are incorrect
  |
note: function defined here
 --> fail_value_ref.rs:1:4
  |
1 | fn show(x: i32) {
  |    ^^^^ ------
help: consider removing the borrow
  |
6 -     show(&n);
6 +     show(n);
  |

error: aborting due to 1 previous error

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

Here the help proposes removing the borrow — passing the value itself rather than the reference to it, which works at this call because the original variable is still in hand and i32 is a Copy type, so passing it copies it. Where only the reference is in hand, the equivalent repair is dereferencing, *r: following the reference to the value behind it and copying that value out. For a type that is not Copy, dereferencing a shared reference cannot move the value out, and the compiler will say so with a different error; the repair then is to change the callee to take the reference — usually the right design anyway — or to clone the value behind the reference deliberately.

This family is where the coercion boundary from the rule section earns its keep a second time. Some reference mismatches never appear, because a coercion covers them: &mut T where &T is expected, &String where &str is expected, &Vec<T> where &[T] is expected, &[T; N] where &[T] is expected. Others always appear: T where &T is expected, &T where T is expected, &mut T where a second &mut T is no problem at all but an owned T is still a mismatch. The pattern is the one the Reference draws: coercions adjust references to other references at specific sites; they never create a borrow the code did not write, and never discard one it did. When a reference-form E0308 appears, the fix is therefore always explicit and always one of two characters deep: add the & that borrows, or add the * that follows the borrow to its value — after checking, as with strings, whether the signature rather than the call is the side misstating what it needs.

The fifth failure: the semicolon that returns ()

The most disproportionate form of E0308 — one character of punctuation producing an error about the function's whole return type — comes from Rust's expression-based design. The Book's functions chapter draws the distinction the error rests on: statements perform an action and do not return a value; expressions evaluate to a value; and if you add a semicolon to the end of an expression, you turn it into a statement, which then does not return a value. A function returns the value of its final expression — unless that expression has been semicolon-terminated, in which case the body evaluates to the unit type:

Rust
fn plus_one(x: i32) -> i32 {
    x + 1;
}
fn main() {
    let x = plus_one(5);
    println!("x = {x}");
}
Terminal
$ rustc --edition 2021 fail_semicolon.rs -o fail_semicolon
error[E0308]: mismatched types
 --> fail_semicolon.rs:1:24
  |
1 | fn plus_one(x: i32) -> i32 {
  |    --------            ^^^ expected `i32`, found `()`
  |    |
  |    implicitly returns `()` as its body has no tail or `return` expression
2 |     x + 1;
  |          - 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`.

Read this diagnostic from the signature line, not from the body. The underlines sit on the return type itself, the note states that the function implicitly returns () because its body has no tail expression, and only then does the help point at the semicolon to remove. The error is reported against the declaration because that is where the expectation lives; the defect is one line below and one character wide. This is the one form of E0308 where the correct response is always mechanical: the help is right, remove the semicolon — or, if the function genuinely returns nothing, remove the return declaration instead and let the signature tell the truth. The same unit mismatch appears anywhere a block's tail expression is accidentally terminated: an if arm, a match arm, a closure body. Whenever an E0308 reports found () and the code plainly computes a value, look for the semicolon before looking anywhere else.

The remaining forms: floats, arrays, and conditions

Three smaller forms complete the survey, each a special case of a section above.

A floating-point literal cannot meet an integer annotation. There is no rounding rule to appeal to — Rust does not truncate a float into an integer implicitly, because choosing between truncation, rounding, and rejection is a program decision:

Rust
fn main() {
    let x: i32 = 3.5;
    println!("x = {x}");
}
Terminal
$ rustc --edition 2021 fail_float_int.rs -o fail_float_int
error[E0308]: mismatched types
 --> fail_float_int.rs:2:18
  |
2 |     let x: i32 = 3.5;
  |            ---   ^^^ expected `i32`, found floating-point number
  |            |
  |            expected due to this

error: aborting due to 1 previous error

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

An array literal is a meeting point of its elements, exactly as a branch is a meeting point of its arms: every element must share one type, and the first element sets the expectation the later elements are checked against. A suffixed literal in the wrong company therefore fails even though each literal alone is unobjectionable:

Rust
fn main() {
    let a = [1i32, 2i64, 3];
    println!("a = {a:?}");
}
Terminal
$ rustc --edition 2021 fail_array_mixed.rs -o fail_array_mixed
error[E0308]: mismatched types
 --> fail_array_mixed.rs:2:20
  |
2 |     let a = [1i32, 2i64, 3];
  |                    ^^^^ expected `i32`, found `i64`
  |
help: change the type of the numeric literal from `i64` to `i32`
  |
2 -     let a = [1i32, 2i64, 3];
2 +     let a = [1i32, 2i32, 3];
  |

error: aborting due to 1 previous error

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

And a condition is a meeting point with a fixed expectation. The error codes index's own examples include an if condition of the wrong type, and the Book's control-flow chapter shows the same failure: an if condition must be a bool, and Rust will not convert a non-Boolean value into one — there is no truthiness for integers, pointers, or strings:

Rust
fn main() {
    let number = 3;
    if number {
        println!("number was three");
    }
}
Terminal
$ rustc --edition 2021 fail_condition.rs -o fail_condition
error[E0308]: mismatched types
 --> fail_condition.rs:3:8
  |
3 |     if number {
  |        ^^^^^^ expected `bool`, found integer

error: aborting due to 1 previous error

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

The repair is to write the comparison the program meant: number != 0, number > 0, or whichever predicate the branch actually tests. Of all the forms in this guide, this is the one where the missing conversion most clearly was a missing thought: the compiler cannot know which comparison an integer condition intended, so it asks, in the only way it can, by refusing.

Fix 1: change the type where it is declared — annotation, suffix, and signature

The first fix to reach for changes no value at all. It corrects the side of the disagreement that was misstated: the annotation that pinned a variable to the wrong integer type, the literal that needed a suffix, the local declaration that should have matched the return type from the start. This fix is first because it is free at runtime — no conversion executes, no allocation happens — and because a large share of real E0308 errors are declaration errors: the program's data was always the right shape, and one written type somewhere disagrees with the rest.

For literals and parsed values, the instruments are the annotation, the suffix, and the turbofish — the ::<...> syntax that supplies a generic parameter explicitly at a call:

Rust
fn takes_i64(x: i64) -> i64 { x }
fn main() {
    let a = takes_i64(5);
    println!("a = {a}");
    let b: i64 = 5;
    println!("b = {b}");
    let c = 5i64;
    println!("c = {c}");
    let parsed: i32 = "42".parse().expect("not a number");
    println!("parsed = {parsed}");
    let parsed2 = "7".parse::<i64>().expect("not a number");
    println!("parsed2 = {parsed2}");
}
Terminal
$ rustc --edition 2021 fix_annotation.rs -o fix_annotation
$ ./fix_annotation
a = 5
b = 5
c = 5
parsed = 42
parsed2 = 7

The first three lines of output are one lesson in three spellings: a bare literal passed to an i64 parameter adapts on its own; the same value bound with an i64 annotation and with an i64 suffix is the same value with its type stated at the declaration instead of inferred at the use. The last two lines show the pair of spellings for the one place literals cannot help: parsing, where the target type exists nowhere in the text being parsed. The annotation on parsed and the turbofish on parsed2 state the identical fact in the two positions Rust allows — on the binding, or on the call — and either one turns an inference failure or a wrong-type result into the type the program needs. When an E0308 involves a generic function — collection literals, parse, collect, into with an ambiguous target — restating the type in one of these positions is usually the entire fix.

The signature variant of this fix changes the function's declared parameter or return type to the type its callers and its body already agree on. It is the right repair when every call site passes the same "wrong" type, or when the body computes one type and the declaration names another out of habit — the wide return in the second section's failure, narrowed. Changing a signature is a design act with callers on the other side of it; reach for it when the signature is the outlier, not merely when it is the side the compiler underlined.

Fix 2: convert with From and Into where the conversion cannot lose

When the signature is right and the value's type is right and the two simply differ, the conversion must be written — and the first conversion family to reach for is the one that cannot go wrong. The From trait is for value-to-value conversions that are perfect: the documentation for its fallible counterpart states the boundary exactly, that From is intended for perfect conversions, which is why no From exists from i64 to i32 — an i64 may hold a value an i32 cannot represent, so the conversion would lose data. Implementing From for a pair automatically provides Into for the same pair, and the two spellings differ only in which type the code names: i64::from(n) names the target at the conversion, n.into() names it at the destination. The compiler's own help in the canonical failure proposed .into() for exactly this reason:

Rust
fn total(x: i64) -> i64 { x + 1 }
fn main() {
    let n: i32 = 5;
    let t = total(i64::from(n));
    println!("t = {t}");
    let m: i64 = n.into();
    println!("m = {m}");
    let f: f64 = f64::from(n);
    println!("f = {f}");
}
Terminal
$ rustc --edition 2021 fix_from_into.rs -o fix_from_into
$ ./fix_from_into
t = 6
m = 5
f = 5

Every conversion in this program is total: every i32 is an i64, every i32 is an f64, and no input exists for which the conversion fails or approximates. The standard library provides From between integer types in the widening direction — smaller to larger at the same signedness, and the unsigned-to-signed widenings that always fit, such as u8 to i32 — between &str and String in the owning direction, and from a value to itself. The rule for reaching here first is verifiability at a glance: if the conversion is in the From family, its losslessness is a library guarantee, not a property of the current input. The moment the pair you need is absent from that family, the absence itself is information — the conversion can lose — and the next fix is the one that makes the possible loss explicit.

Fix 3: try the conversion that can fail — TryFrom and TryInto

For narrowing and sign-changing conversions, the standard library provides the fallible pair. TryFrom performs simple and safe type conversions that may fail in a controlled way, and it is the reciprocal of TryInto: implementing one provides the other. Where From returns the target type, TryFrom returns a Result of the target type and an error, so the program must decide what a value that does not fit means — reject it, clamp it, report it — instead of receiving a silently altered number:

Rust
fn main() {
    let big: i64 = 3;
    let small = i32::try_from(big);
    println!("small = {small:?}");
    let huge: i64 = 1_000_000_000_000;
    let attempt = i32::try_from(huge);
    println!("attempt is_err = {}", attempt.is_err());
    match i32::try_from(huge) {
        Ok(v) => println!("narrowed = {v}"),
        Err(e) => println!("cannot narrow {huge} to i32: {e}"),
    }
    let ok_val: i64 = 42;
    let narrowed: i32 = ok_val.try_into().expect("value fits in i32");
    println!("narrowed = {narrowed}");
}
Terminal
$ rustc --edition 2021 fix_tryfrom.rs -o fix_tryfrom
$ ./fix_tryfrom
small = Ok(3)
attempt is_err = true
cannot narrow 1000000000000 to i32: number too large to fit in target type
narrowed = 42

The output states both halves of the contract. The small value narrows to Ok(3). The trillion-value input fails: is_err reports true, and the error message names the reason in plain terms — the number is too large to fit in the target type. The final lines show the try_into spelling succeeding on a value that fits, with expect standing in for whatever real handling the program owes the failure case. Reach for this fix whenever the received type is wider than the expected type or the signedness differs: i64 to i32, usize to u32, i32 to u32, lengths and counts crossing an API boundary. It is also the fix to prefer at trust boundaries — file formats, network values, user input — where the wide value is not merely wide but unvalidated, and a conversion that can fail is a check the program needed anyway.

Fix 4: build the owned string — to_string, String::from, and formatting

The string family's conversion is an allocation, and its spellings are worth separating because they signal different intentions to a reader. to_string converts any value with a Display implementation into an owned String; on a &str it copies the text into a new buffer. String::from is the From conversion for the same pair, naming the target type at the call. format! builds an owned string from a template and values, for the common case where the text being passed is assembled rather than copied:

Rust
fn greet(name: String) {
    println!("hello, {name}");
}
fn takes_slice(name: &str) {
    println!("hello, {name}");
}
fn main() {
    greet("Ada".to_string());
    greet(String::from("Grace"));
    let owned = String::from("Linus");
    takes_slice(&owned);
    takes_slice("Margaret");
    let s: String = "hello".to_string();
    println!("s = {s}");
}
Terminal
$ rustc --edition 2021 fix_string.rs -o fix_string
$ ./fix_string
hello, Ada
hello, Grace
hello, Linus
hello, Margaret
s = hello

All five calls in this program print. The first two build the owned string the String parameter demands, by the two spellings above. The next two call the &str function — one with a borrowed owned string, which coerces to a view with no allocation and no conversion written, and one with a literal directly. The last line discharges the annotation form of the failure the same way the first line discharged the argument form. The pricing note from the failure section stands: each owned conversion allocates a buffer proportional to the text, which is correct when the callee keeps or grows the text and waste when it only reads. Audit the parameter before paying at the call sites — a &str parameter is this family's Fix 1, and it removes the conversion rather than performing it.

Fix 5: borrow or dereference — repair the access, not the value

When the mismatch is between a value and a reference to it, nothing about the value needs to change; the access path does. Borrowing at the call meets a &T parameter, and dereferencing follows a reference to the Copy value behind it:

Rust
fn show_ref(x: &i32) {
    println!("x = {x}");
}
fn show_val(x: i32) {
    println!("x = {x}");
}
fn main() {
    let n = 5;
    show_ref(&n);
    let r = &n;
    show_val(*r);
    println!("n = {n}");
}
Terminal
$ rustc --edition 2021 fix_borrow_deref.rs -o fix_borrow_deref
$ ./fix_borrow_deref
x = 5
x = 5
n = 5

The three printed lines are the two repairs and the proof that neither consumed anything: the borrow lends n and returns it untouched, the dereference copies the integer out of the reference and leaves both the reference and n valid, and the final line prints the original. The third access repair writes nothing at all: it relies on the coercions the rule section cataloged. A function that takes a slice accepts a reference to a vector; a function that takes &str accepts a reference to a String; a &i32 binding can be initialized from a &mut i32:

Rust
fn first(items: &[i32]) -> i32 { items[0] }
fn shout(s: &str) -> String { s.to_uppercase() }
fn main() {
    let v = vec![10, 20, 30];
    println!("first = {}", first(&v));
    let owned = String::from("hello");
    println!("shout = {}", shout(&owned));
    let mut n = 5;
    let r: &i32 = &mut n;
    println!("r = {r}");
}
Terminal
$ rustc --edition 2021 fix_coercion.rs -o fix_coercion
$ ./fix_coercion
first = 10
shout = HELLO
r = 5

This program is the boundary of the whole error, drawn in running code. References bend — through dereference targets, through unsizing, from mutable to shared — because those adjustments change only how the same value is viewed, at the specific sites the Reference lists. Values do not bend, because changing a value's type changes what it is. When an E0308 survives an attempted fix, it is almost always because the fix tried to bend a value; the repairs that work either restate the value's type at its declaration, convert it by one of the three conversion families, or adjust the access to it. There is no fourth mechanism, which is what makes the error's decision table below short enough to memorize.

Fix 6: cast with as — the conversion that always answers and sometimes lies

The last conversion is the one that never refuses. The as operator performs the explicit version of the permitted coercions and, beyond them, a large family of numeric casts: between any two integer types, between integers and floats, between char and integers, and more. It is the fix the canonical failure did not need — a lossless From existed — and it is the correct fix in the narrow band where a cast's semantics are exactly what the program means: reinterpreting a value at a boundary the program controls, extracting a byte, feeding a foreign interface its expected width:

Rust
fn total(x: i64) -> i64 { x + 1 }
fn main() {
    let n: i32 = 5;
    let t = total(n as i64);
    println!("t = {t}");
    let wide: i64 = 7;
    let back = wide as i32;
    println!("back = {back}");
}
Terminal
$ rustc --edition 2021 fix_as_cast.rs -o fix_as_cast
$ ./fix_as_cast
t = 6
back = 7

Used there, on values the program knows fit, the cast is honest and cheap, and for some pairs — a char to its code point, an enum to its discriminant type — it is the only spelling. Its danger is the subject of the trap below, and the discipline is a single question asked of every as in a diff: what does this cast do to the largest and smallest values the received type can hold? If the answer is "nothing, they all fit," the cast is a widening that From probably spells better. If the answer names a loss, the program must be able to say the loss is intended — and if it cannot, TryFrom is the fix that was actually needed.

The traps: casting a narrowing into silence, and converting the wrong side forever

Trap
Two responses to E0308 compile while damaging the program, and both are tempting because both are small edits at the error site.

The first is reaching for as at a narrowing. A cast cannot fail, so it cannot report the value that did not fit; it truncates, wraps, or saturates according to the cast's defined rules, and the program continues with a different number than it was handed. This program compiles cleanly and runs to completion — every line of its output is a value the program never contained:

Rust
fn main() {
    let big: i64 = 1_000_000_000_000;
    let small = big as i32;
    println!("big as i32 = {small}");
    let wide = 300;
    let byte = wide as u8;
    println!("300 as u8 = {byte}");
    let neg: i32 = -1;
    let unsigned = neg as u32;
    println!("-1i32 as u32 = {unsigned}");
    let frac: f64 = 3.99;
    let whole = frac as i32;
    println!("3.99 as i32 = {whole}");
}
Terminal
$ rustc --edition 2021 trap_as_lossy.rs -o trap_as_lossy
$ ./trap_as_lossy
big as i32 = -727379968
300 as u8 = 44
-1i32 as u32 = 4294967295
3.99 as i32 = 3

A trillion became negative seven hundred million. Three hundred became forty-four, because a byte holds values only up to 255 and the cast kept the low eight bits. Negative one became the largest u32. A float just below four became three, because float-to-integer casts truncate toward zero. None of these is a malfunction; each is the documented behavior of its cast. The malfunction is choosing an instrument that answers every question with a number when the program needed an instrument that can answer "this does not fit" — which is TryFrom, returning its error for the same trillion input in the fix above. The TryFrom documentation makes the contrast itself, showing the same large value silently truncating under as and returning an error under try_from. A cast in a diff is a claim that the loss cannot happen or does not matter; a reviewer should be able to ask for the proof of that claim and receive it in one sentence.

The second trap is converting the value at every call site when the signature is the side that is wrong. A function that only reads a string takes String, and a dozen callers grow .to_string() calls, each allocating, each repeating the same compensation for one misstated parameter. A function returns i64 out of habit, and every caller narrows with a cast or a try_into that can never fail on the values the function actually produces. The error is fixed at every site except the one where it lives. The symptom to recognize is repetition: the same conversion, applied to the same boundary, in more than two places, is the signature asking to be changed — to &str, to the narrower integer, to the type the other side of the boundary already speaks. E0308 reports each meeting separately, so a boundary defect presents as many errors; fixing the declaration fixes the family.

A boundary case completes the map, labeled with its own code so it is not mistaken for this guide's error. Reaching for From on a narrowing pair does not produce E0308; it produces a trait error, because the conversion does not exist:

Rust
fn main() {
    let big: i64 = 5;
    let small: i32 = i32::from(big);
    println!("small = {small}");
}
Terminal
$ rustc --edition 2021 fail_from_narrow.rs -o fail_from_narrow
error[E0277]: the trait bound `i32: From<i64>` is not satisfied
 --> fail_from_narrow.rs:3:22
  |
3 |     let small: i32 = i32::from(big);
  |                      ^^^ the trait `From<i64>` is not implemented for `i32`
  |
  = help: `i32` implements trait `From<T>`:
            From<bool>
            From<i16>
            From<i8>
            From<u16>
            From<u8>

error: aborting due to 1 previous error

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

The code is E0277 — the trait bound is not satisfied — and its help usefully lists the From implementations that do exist for the target, the lossless widenings arriving from the smaller types. Read that list as the library stating its policy in the diagnostic itself: these are the conversions guaranteed perfect; the one you asked for is not among them because it cannot be guaranteed; the fallible family is where it lives. Three codes, three different defects: E0308, two types met and disagreed; E0317, a branch arm was never written; E0277, the conversion asked for does not exist. The first line of the diagnostic tells you which repair family you are in before you read a line of code.

Which fix for which error

What the diagnostic shows What is actually happening First fix to reach for
Argument of type i32, parameter of type i64 (or any widening pair) The value's type is fixed narrower than the signature; a lossless conversion exists Fix 2 — From or Into conversion at the call; or Fix 1 — redeclare the value at the wider type
Return expression's type differs from the -> declaration The body and the signature disagree inside one function Decide which side is the contract; convert the tail expression, or Fix 1 — correct the declaration
Signed value meets unsigned parameter, or wide meets narrow The conversion can lose or reject values; no From exists Fix 3 — TryFrom or TryInto, with the failure case handled
if and else have incompatible types The two arms produce different types and the result must have one Decide the result type once; convert the arm that disagrees — often by formatting a number into text
match arms have incompatible types One arm breaks the common type the other arms established Bring the breaking arm to the common type, or change the common type deliberately in every arm
Expected a value, found () in an arm or a tail expression A block or arm produced unit: an empty arm, or a semicolon terminated the tail expression Give the arm its value; for a function tail, remove the semicolon (Fix from the fifth failure)
E0317: if may be missing an else clause A value-producing if has no else; without one it evaluates to () Add the else arm with the fallback value, or stop using the if as an expression
Expected String, found &str The callee claims ownership; the caller has only a view Fix 4 — .to_string() or String::from at the call; first check whether the parameter should be &str
Expected &str, argument is a String value The callee wants a view; the caller is offering ownership Pass &value — the borrow coerces to &str with no allocation (Fix 5)
Expected &T, found T — or expected T, found &T The access path disagrees, not the value Fix 5 — borrow with & at the call, or dereference with * where the value is Copy
Expected bool, found an integer as a condition The program relied on a truthiness Rust does not have Write the comparison the branch means: x != 0, x > 0
Expected an integer, found a float No implicit rounding or truncation exists Decide the rule — as to truncate deliberately, or restructure so the value is computed as an integer
A literal or a parse result has the wrong or unknown type Inference had no fixed type to work from Fix 1 — annotation, suffix, or turbofish stating the type once
E0277: the From trait is not implemented for the pair The conversion asked for is not a perfect conversion Fix 3 — the fallible family, TryFrom and TryInto

Checklist

  • Read the first line of the diagnostic literally: it names the expected type, the received type, and the meeting point. Those three facts select the repair family before any code is read.
  • Ask of every mismatch which side owns the truth: the signature, the annotation, or the value. Convert the side that is wrong; never convert both, and never convert the right side to meet a misstated declaration.
  • Check whether the conversion you need is perfect. If a From implementation exists for the pair, use it — its existence is the library's guarantee that nothing can be lost.
  • If no From exists for the pair, treat the absence as the diagnosis: the conversion can fail or lose. Use TryFrom, and write the failure branch as a real decision, not an unwrap that moves the refusal to runtime.
  • Price every as cast with its extreme values: the largest, the smallest, and a negative if the source is signed. If any of them comes out wrong and the program would not want that, the cast is the trap, not the fix.
  • In branches, decide the result type once and bring every arm to it. An arm converted in isolation, without the decision, produces the next mismatch one arm over.
  • When the diagnostic reports found (), look for punctuation before types: a semicolon on a tail expression, an empty arm, a statement where the value was meant to be.
  • When the code is E0317 rather than E0308, the arm is missing, not mismatched: add the else, or stop using the branch as an expression.
  • With strings, audit the parameter before paying at the call sites. A read-only &str parameter removes the error for all callers; a String parameter makes every caller allocate, and that should be a decision, not a default.
  • With references, remember the boundary: coercions adjust references to references at argument, binding, and return sites, and never create or discard a borrow. Write the & or the * yourself.
  • If the same conversion appears at the same boundary in more than two places, change the declaration at the boundary instead. Repetition is the signature asking to be fixed.
  • After the fix, reread the code for the question the error was asking: at this meeting point, what type does each side have, and where in the program is the conversion between them written?
  • Fix Rust E0382 "borrow of moved value" — the companion repair manual for the ownership error: a value that was given away and then used, where this guide is the manual for two types that met and disagreed.
  • Rust Ownership and Borrowing — the concepts guide behind both errors: moves, borrows, and the ownership rules that decide which conversions a signature is really asking for.

Sources

  • Rust Project, Error codes index: E0308 — for the definition of E0308 as an expected type not matching the received type, for the index's own examples of a wrong argument type, a non-Boolean condition, and a wrongly typed binding, and for the statement that the error most commonly occurs when an argument's type differs from the function declaration.
  • Rust Project, The Rust Programming Language: Data Types — for Rust as a statically typed language in which every variable has a single type known at compile time, for the integer type table and the i32 default, and for the unit type () as the empty return type.
  • Rust Project, The Rust Programming Language: How Functions Work — for the statement and expression distinction, for a trailing semicolon turning an expression into a statement that returns no value, and for the Book's own E0308 example of a function whose semicolon-terminated body implicitly returns () against an i32 declaration.
  • Rust Project, The Rust Programming Language: Control Flow — for the rule that the result values of an if expression's arms must be the same type, for the Book's E0308 examples of mismatched arms and of a non-Boolean condition, and for variables having a single type known definitively at compile time.
  • Rust Project, The Rust Reference: Type coercions — for coercions as implicit operations restricted to specific coercion sites, for the permitted conversions between reference and pointer types and through Deref, for unsized coercions from arrays to slices, and for least-upper-bound coercion as the mechanism that finds a common type for branch arms.
  • Rust Project, std::convert::TryFrom — for fallible conversions that may fail in a controlled way, for the absence of a From conversion from i64 to i32 because it would lose data, for From as the trait of perfect conversions, and for the documented contrast between an as cast silently truncating a large value and try_from returning an error for it.

Keep Exploring