Sub topic 5
The unit type and one-element tuples
This chapter assumes you can read tuple types such as (i32, f64), write functions with return types, and use Result and Option at a basic level. It covers the smallest tuples: the empty tuple () and the tuple with one element.
The unit type
The unit type is written () and is also called the empty tuple. It has exactly one value, which is also written (). A value of this type carries no information, so it takes no memory.
You use it all the time without writing it. A function with no -> return type returns (). An expression followed by a semicolon is a statement, and a statement evaluates to ().
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, a == b);
println!("{}", std::mem::size_of::<()>());
}The two functions have the same signature. a == b is true because () has only one value. size_of::<()>() prints 0.
Why unit is useful
Unit lets "no meaningful value" fit into generic code. The most common case is Result<(), E>: the operation either succeeds with nothing to report or fails with an error.
fn check_age(age: u32) -> Result<(), String> {
if age >= 18 {
Ok(())
} else {
Err(format!("{age} is too young"))
}
}
fn main() {
println!("{:?}", check_age(20));
println!("{:?}", check_age(12));
}This prints Ok(()) and then Err("12 is too young"). The Ok(()) is the Ok variant wrapping the unit value.
One-element tuples
A tuple with one element needs a trailing comma. Without the comma, the parentheses are only grouping.
fn main() {
let not_tuple = (5);
let one = (5,);
println!("{} {:?} {}", not_tuple, one, one.0);
}(5) is an i32, and (5,) is a (i32,). The program prints 5 (5,) 5. The compiler also warns that the parentheses in (5) are unused, which is a useful hint that you wrote a plain value.
The same rule applies to types. (i32,) is a one-element tuple type, and (i32) is just i32.
Summary of the three forms
| Expression | Type | Meaning |
|---|---|---|
| `()` | `()` | The unit value, zero elements |
| `(5)` | `i32` | A parenthesized integer |
| `(5,)` | `(i32,)` | A tuple with one element |
One-element tuples are rare in everyday code. They appear mostly when a generic API expects a tuple of any length, and when a macro or iterator produces them.
Exercise
Why does let x = (3.5); give a f64 and not a tuple, and what change makes it a tuple? What is the type of a block { let y = 2; }?
Show answer
Parentheses without a comma only group an expression, so (3.5) is the f64 value 3.5. Writing (3.5,) makes a one-element tuple of type (f64,). The block { let y = 2; } ends in a statement with a semicolon and has no tail expression, so its type is ().