liveBook · Manning

Unit type

As explained in Learn Rust in a Month of Lunches

A unit type is a type with exactly one value, commonly written (), that represents the absence of meaningful information or a meaningful result.

The unit type is Rust’s type for “nothing meaningful.” It has one value, written as (), and commonly represents a function that receives no useful input or returns no useful result. An empty function body is shorthand for returning (). section 3.1.3

A semicolon changes the return value

Rust uses the final expression of a function as its return value when that expression has no semicolon. Thus, `fn give_number() -> i32 { 8 }` returns an integer, while adding a semicolon makes the body return `()`. The compiler reports this mismatch as “expected `i32`, found `()`” and suggests removing the semicolon. Writing `fn do_something() -> () {}` makes the unit return type explicit, although `fn do_something() {}` is the shorter form. section 1.6 section 3.1.3

Use the unit type to read ordinary Rust function code:

  • A function with no parameters uses empty parentheses: `fn do_something()`. section 3.1.3
  • A function with no meaningful result returns `()` implicitly or explicitly. section 3.1.3
  • A statement ending in `;` produces no useful value, so its value is `()`. section 1.6
  • A final call returning `()` can become the enclosing function’s final result, although adding a semicolon often makes the intent clearer. section 3.1.3
fn do_something() -> () {}

Compare the explicit unit return type with the shorter function form to see that both describe a function returning nothing. section 3.1.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines the unit type, traces semicolon-driven return behavior, and interprets compiler feedback without exploring deeper type-system internals.
Examples
Uses empty functions, an integer-returning function with and without a semicolon, and a function call returning unit.
What it assumes
Assumes basic Rust functions and expressions while teaching empty tuples, implicit returns, and semicolon effects directly.
What you can do after
Build it from scratch by writing functions that explicitly or implicitly return the unit type and correcting semicolon mismatches.
How it connects
Connects the unit type to functions, return expressions, semicolons, tuples, and compiler type checking.

Also explained in

Compare how 7 books explain unit type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.