liveBook · Manning

Unit type

As explained in Rust in Action: Systems programming concepts and techniques

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

The unit type, written `()`, means there is no meaningful value to return. It is a zero-length tuple with exactly one value, also written `()`. A function with no stated return type returns unit implicitly; it can also declare `-> ()`. section 3.1 section 1.6.2

A function that returns unit

`fn report<T: Debug>(item: T) { println!("{:?}", item); }` prints an item but returns no meaningful value. `fn clear(text: &mut String) -> () { *text = String::from(""); }` states its unit return type explicitly. section 3.1

A semicolon matters when a function is meant to return a value. An `add` function whose final expression is `i + j` returns an `i32`; putting a semicolon after that expression makes the function return `()` instead. section 2.2.1 section 3.1

Unit also helps explain a compiler error. An `if` condition needs a Boolean value. Writing `if a = 10` uses assignment, whose result is `()`, rather than the comparison `a == 10`. The compiler therefore reports “expected `bool`, found `()`.” section 1.6.2 section 2.4.6

error[E0308]: mismatched types
 --> src/main.rs:4:8
  |
4 |     if a = 10 {
  |        ^^^^^^
  |        |
  |        expected `bool`, found `()`
  |        help: try comparing for equality: `a == 10`
 
error: aborting due to previous error
 
For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`.
 
To learn more, run the command again with --verbose.

The compiler message pinpoints the mistaken `=` and suggests `==`, showing why unit is not a valid `if` condition. section 1.6.2

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Defines unit as a zero-length tuple with one value and works through implicit returns, explicit returns, and semicolon mistakes.
Examples
Uses an assignment-versus-comparison compiler error, a printing function, and a string-clearing function.
What it assumes
Introduces unit while teaching basic functions and conditionals, without relying on advanced Rust features.
What you can do after
Diagnose/debug with it when a compiler error reports `()` where a Boolean or another return type is expected.
How it connects
Connects unit to tuples, function return types, expression statements, semicolons, and Boolean conditions.

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 Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.