skip to content

Why does rustc reject a Rust `fn parse_port(s: &str) -> u16` with E0308 when its last line ends in a semicolon?

level: middleimportance: must knowfreq 66%

answer

  1. statement versus expression
  2. what a block evaluates to
  3. the block's final operand
  4. no tail means unit
  5. help: remove this semicolon

basics

~20 s

A block's value is its final expression written without a semicolon. The semicolon turns that line into a statement, so the body has no final operand, evaluates to (), and fails with E0308 against the declared u16.

solid answer

~40 s

Rust is expression-oriented: a block `{ ... }` runs its statements and then evaluates to its final operand, the trailing expression with no semicolon, and a function body is such a block. So `trimmed.parse::<u16>().unwrap_or(8080)` as the last line is the return value. With a semicolon it becomes an expression statement whose result is discarded; the block then has no final operand and its type is the unit type `()`. rustc reports E0308, "expected `u16`, found `()`", notes that the function "implicitly returns `()` as its body has no tail or `return` expression", and suggests removing the semicolon. `return value;` is fine, because a block that ends by diverging has type `!`, which coerces to `u16`.

code

rust · 8 lines
rust
fn parse_port(s: &str) -> u16 {
    let trimmed = s.trim();
    trimmed.parse::<u16>().unwrap_or(8080);
}

fn main() {
    println!("{}", parse_port(" 9000 "));
}

go deeper

for a junior

Recall that the last expression of a block, written without a semicolon, is the block's value and therefore a function's return value.

for a middle

Explain the three block cases (final operand, unit, diverging) and read the E0308 found () message straight to the stray semicolon.

for a senior

Recognise the same mistake in disguise: a closure in map producing Vec of unit, an if without else (E0317), or a value-typed if used as a statement.

for a principal

Lean on expression-oriented style in reviews: values computed by blocks and ifs instead of uninitialised variables assigned in branches, which keeps every binding immutable.

## Expressions and statements An **expression** produces a value; a **statement** performs an action and produces nothing usable. The Reference's grammar has a handful of statement forms; the ones that matter here: - **Item declarations**, such as a nested `fn` or `struct`. - **`let` statements**, which introduce bindings. - **Expression statements**: an expression followed by `;`. The Reference defines it as one that "evaluates an expression and ignores its result". - The empty statement `;`, which does nothing. Almost everything else, including blocks, `if`, `match` and function calls, is an expression. That is why `let port = if tls { 443 } else { 80 };` works without a ternary operator. ## A block evaluates to its final operand A **block expression** is `{`, any number of statements, an optional **final operand**, and `}`. The Reference states the rule in three cases: 1. With a final operand, "the block has the type and value of that final operand". 2. Without one, and if the block does not diverge, "the block has unit type and unit value". 3. Without one, and if every path diverges (a `return`, a `panic!`, an endless `loop`), the block has the never type `!`. A function body is a block, so its final operand is the function's return value; no `return` keyword is needed. ```rust fn parse_port(s: &str) -> u16 { let trimmed = s.trim(); trimmed.parse::<u16>().unwrap_or(8080) // final operand: the body's value } fn early(s: &str) -> u16 { return s.trim().parse::<u16>().unwrap_or(8080); // diverges, so `;` is fine } fn main() { let port = { let raw = " 9000 "; raw.trim().parse::<u16>().unwrap_or(8080) }; let nothing = { let _twice = port * 2; }; // no final operand: unit println!("{} {} {} {:?}", parse_port("443"), early("x"), port, nothing); } ``` It prints: ```plaintext 443 8080 9000 () ``` `early` keeps its semicolon and still compiles: its body ends in a diverging `return`, so it falls under case 3, not case 2. ## What the stray semicolon does Add `;` after the last line of `parse_port` and that line becomes an expression statement: the parsed port is computed and thrown away. The body now has no final operand, so it is `()`, and the declared return type is `u16`. rustc 1.99.1 prints: ```plaintext error[E0308]: mismatched types --> e1.rs:1:27 | 1 | fn parse_port(s: &str) -> u16 { | ---------- ^^^ expected `u16`, found `()` | | | implicitly returns `()` as its body has no tail or `return` expression 2 | let trimmed = s.trim(); 3 | trimmed.parse::<u16>().unwrap_or(8080); | - help: remove this semicolon to return this value ``` The message carries all three parts of the diagnosis: what was expected, why the body is `()`, and the one-character fix. ## The unit type `()` is the **unit type**, a type with exactly one value, also written `()`. It is a real value, not an absence: `let nothing = { let _twice = port * 2; };` binds it, and `{:?}` prints it as `()`. A function with no `-> T` in its signature returns `()`, which is why a body made only of statements compiles there. | Block ends with | Type of the block | Example | |---|---|---| | an expression, no `;` | that expression's type | `{ s.trim().len() }` is `usize` | | a statement (`;`) | `()` | `{ s.trim().len(); }` | | nothing (`{}`) | `()` | `let x: () = {};` | | a diverging statement | `!`, coerces to anything | `{ return 0; }` | ## The same rule in other places - **`if` without `else`.** It evaluates to `()`, so `let port: u16 = if tls { 443 };` fails with E0317, "`if` may be missing an `else` clause", noting that "`if` expressions without `else` evaluate to `()`". - **Closure bodies.** `.map(|s| { s.parse::<u16>().unwrap(); })` returns `()` from each call, so collecting into `Vec<u16>` fails with E0277: the iterator yields `()`. - **Block-like expressions mid-block.** An `if`, `match` or block used as a statement may omit its `;`, but then it must have type `()`. `if c { 1 } else { 2 }` followed by more statements fails with E0308, expected `()`, found integer. - **Unit-returning functions are forgiving.** In `fn log(msg: &str) { println!("{msg}"); }` the semicolon is harmless, because `()` is exactly what the signature asks for. When E0308 says found `()` and the code looks right, look first at the last line of the block the error points to.

  • In Rust, why does `raw.iter().map(|s| { s.parse::<u16>().unwrap(); }).collect::<Vec<u16>>()` fail to compile?
    The closure's body is a block whose last line ends in a semicolon, so each call returns `()` and the iterator yields `()`. rustc reports E0277, "a value of type `Vec<u16>` cannot be built from an iterator over elements of type `()`". Removing the semicolon, or writing `|s| s.parse::<u16>().unwrap()`, makes the parsed value the closure's result.
  • In Rust, why may `if v.is_empty() { v.push(5); } else { v.remove(0); }` stand mid-block without a semicolon, while `if c { 1 } else { 2 }` may not?
    A block-like expression used as a statement may omit its semicolon, but then its type must be `()`. Both branches of the first end in statements, so it is `()`. The second evaluates to an integer, so rustc reports E0308, expected `()`, found integer. Add `;` after it, or use its value.

  • The semicolon after the last line is only style; rustc ignores it.
  • A function needs an explicit `return` to produce a value.
  • `()` means the function returns no value at all, like null.
  • An `if` without `else` evaluates to an `Option` of its branch value.
  • Any block ending in a semicolon is `()`, even when that statement is a `return`.