liveBook · Manning

Unit type

As explained in Refactoring to Rust

The Rust unit type is a type with exactly one value, written as (), that represents the absence of a meaningful value.

The unit type, written as (), has exactly one possible value and carries no information. It represents nothing while remaining a real, distinct type. section 2.5.3 section 2.6

Use () when an operation succeeds without producing a meaningful success value:

  • Functions without an explicit return type return the unit type; writing -> () makes that return explicit. section 2.5.3
  • Result<(), E> reports whether an operation succeeded while carrying no additional information in Ok(()). section 2.5.2 section 2.5.3
  • Unlike null, () is not a substitute for values of other types; assigning it to String produces a type mismatch. section 2.5.3

Printing with fallible control flow

A FizzBuzz printer returns Result<(), &'static str>. Ok(()) means printing completed; Err(e) carries the failure. The caller matches Ok(()) and handles the error. section 2.5.2

Validation with unit results

Validators can return Result<(), ()> when failure has no detail. A surrounding validate_username function uses map_err to convert those unit errors into NotLowercase or NotUnique, then returns Ok(()). section 2.5.5

Listing 2.31 Three functions that all return the unit type
fn foo() {  #1
  println!("Hello!");
}

fn bar() -> () {  #2
  println!("Hello!");
}

fn baz() -> () {
  println!("Hello!");
  ()  #3
}

Compare implicit and explicit unit returns, including an explicit final (). section 2.5.3

How Refactoring to Rust covers it

How deep it goes
Defines the single-value type, contrasts it with null and void, and demonstrates implicit returns and Result usage.
Examples
Uses FizzBuzz printing, Java null comparison, equivalent unit-returning functions, and username validation.
What it assumes
Introduces the concept from zero while contrasting it with familiar null and void representations.
What you can do after
Apply it via Rust function signatures and Result<(), E> to model operations that return success without data.
How it connects
Connects unit values with Result, enums, error handling, map_err, and the question-mark operator.

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 Refactoring to Rust. The section links point to the parts of the book it draws on.