Sub topic 5
The unit type and one-element tuples
This chapter assumes you can write Rust functions, know that a tuple groups values such as (i32, f64), and can read Result<T, E> and Option<T> types. It covers the smallest tuples: the one with zero elements, (), and the one with one element, (T,). Both look like edge cases. Both show up in everyday code.
The unit type is the empty tuple
The unit type is written () and pronounced "unit". It is a tuple with no fields. It has exactly one value, which is also written (). The type and its value share the same spelling, and the compiler tells them apart by position. After a colon or an arrow, () is a type. Anywhere an expression is allowed, () is the value.
Because there is only one possible value, a () carries no information. That is the point. It means "there is nothing meaningful to return here."
fn log(msg: &str) {
println!("{msg}");
}
fn log_explicit(msg: &str) -> () {
println!("{msg}");
}
fn main() {
let a = log("hi");
let b: () = log_explicit("there");
println!("{:?} {:?}", a, b);
println!("{}", a == b);
}The two functions have the same signature. When you leave off -> Type, Rust treats the return type as (). Rust has no void, so a function that "returns nothing" returns the unit value, and you can bind it, print it with {:?}, and compare it. Comparing two units with == is always true, because they cannot differ.
Where unit comes from
You rarely write () by hand. It appears in several places:
- A function with no declared return type.
- A block whose last statement ends with a semicolon.
- An
ifwithout anelse. Its body must evaluate to(). - An assignment expression such as
x = 5, which evaluates to(). - Methods that exist only for side effects, such as
Vec::pushandIterator::for_each.
The second bullet's rule explains a common compiler error. This function does not compile:
fn double_broken(x: i32) -> i32 {
x * 2;
}Rust reports mismatched types: expected i32, found (). The semicolon turns x * 2 into a statement, so the block has no tail expression and evaluates to (). The fix is to remove the semicolon:
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
println!("{}", double(21));
}Unit as a placeholder
Because () has one value, you can use it where a generic type parameter is required but you have nothing to put there. Three common cases:
Result<(), E>means "this either succeeds with no payload or fails withE". You write the success value asOk(()).HashMap<K, ()>stores keys with no associated values. This is howHashSet<K>is built internally.collect()intoResult<(), E>runs a sequence of fallible steps and stops at the first error.
use std::collections::HashMap;
fn check_positive(n: i32) -> Result<(), String> {
if n > 0 {
Ok(())
} else {
Err(format!("{n} is not positive"))
}
}
fn main() {
println!("{:?}", check_positive(3));
println!("{:?}", check_positive(-1));
let all: Result<(), String> = [1, 2, 3]
.iter()
.map(|&n| check_positive(n))
.collect();
println!("{:?}", all);
let bad: Result<(), String> = [1, -2, 3]
.iter()
.map(|&n| check_positive(n))
.collect();
println!("{:?}", bad);
let mut seen: HashMap<&str, ()> = HashMap::new();
seen.insert("a", ());
println!("{}", seen.contains_key("a"));
}The collect calls work because () implements FromIterator<()>. It consumes every () and produces one (). When one item is an Err, Result's own FromIterator implementation returns that error and stops pulling items.
Unit takes no space
A value of a type with only one possible value needs no bits to identify it. Rust therefore stores () in zero bytes. A type with a size of zero is called a zero-sized type.
This is why HashMap<K, ()> is cheap. The value half of each entry costs nothing, and the compiler can remove the reads and writes of it.
One-element tuples need a trailing comma
A tuple with a single element is written (T,) as a type and (value,) as a value. The comma is required. Without it, parentheses are just grouping, the same as in arithmetic:
(5)is the integer5in parentheses.(5,)is a tuple holding one integer.
use std::mem::size_of;
fn main() {
let plain: i32 = (5);
let one: (i32,) = (5,);
println!("{plain}");
println!("{:?}", one);
println!("{}", one.0);
let (inner,) = one;
println!("{inner}");
println!("{} {}", size_of::<()>(), size_of::<(i32,)>());
}The compiler warns that the parentheses around 5 are unnecessary, which confirms that (5) is not a tuple. The Debug output of the tuple is (5,), and it keeps the comma for the same reason. Field access uses .0, and a destructuring pattern also needs the comma: let (inner,) = one;. Writing let (inner) = one; binds inner to the whole tuple, because the parentheses are only grouping.
size_of::<(i32,)>() prints 4. A one-element tuple has the same size as its element, so wrapping costs nothing at runtime.
Why use a one-element tuple
You will not write (T,) often. It is useful in three situations:
- Generic code over tuples. A trait implemented for tuples of every length from 0 to 12 includes the 1-tuple. Examples are
Debug,PartialEq,Ord,Default, andHash. - APIs that take a tuple. Some libraries accept a tuple of parameters, such as a query builder taking
(id,)for one bound parameter. You must pass(id,)and not(id). - Distinguishing a wrapper. A 1-tuple is a quick anonymous wrapper. If you plan to keep it, a named tuple struct such as
struct Meters(f64);communicates intent better.
Both () and (T,) get the usual tuple traits when their elements do. () implements Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, and Default. Default::default() for () is ().
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `expected i32, found ()` at the end of a function | Trailing semicolon on the tail expression | Remove the semicolon |
| `expected tuple, found i32` when passing `(x)` | `(x)` is only `x` in parentheses | Write `(x,)` |
| `let (a) = t;` binds the whole tuple | Pattern lacks the comma | Write `let (a,) = t;` |
| `if` without `else` used as a value | A missing branch is `()`, which clashes with other types | Add an `else` that returns the same type |
| Warning about `let_unit_value` from Clippy | Binding the result of a function that returns `()` | Call the function without a `let` |
The if case shows how unit fits into the type system. Rust treats a missing else as else { }, which has type (). So let n = if flag { 1 }; fails, because 1 is an integer and the missing branch is ().
Exercise
Given let a = (7); let b = (7,); let c = ();, what is the type of each variable? Then explain why fn f(x: i32) -> i32 { x + 1; } fails to compile and how to fix it.
Show answer
a is i32, because the parentheses only group. b is (i32,), a tuple with one element. c is (), the unit type. The function fails because x + 1; ends with a semicolon, so it is a statement and the block evaluates to () where i32 is expected. Removing the semicolon, so that x + 1 is the tail expression, fixes it.
Exercise
Write a function validate_all(values: &[i32]) -> Result<(), String> that returns Ok(()) when every value is non-negative and otherwise returns the first error message, using collect as in this chapter. What does collect produce on an empty slice?
Show answer
One solution is values.iter().map(|&v| if v >= 0 { Ok(()) } else { Err(format!("{v} is negative")) }).collect(). On an empty slice there are no items to fail, so collect returns Ok(()).