Rust Reference ยท Primitive Types
Rust unit type ()
Reference for Rust's unit type (): the empty tuple returned by functions without a result, Result<(), E>, zero size, trailing semicolons and trait support.
The unit type, written (), has exactly one value, also written (). It is the empty tuple. It means "no meaningful value": a function with no declared return type returns (), a block that ends in a statement evaluates to (), and Ok(()) says "success, nothing to report".
Because () is an ordinary type, it fits everywhere a type can go: in generics, in Result<(), E>, as the value type of a map that only needs keys, or as the output of a closure. It takes zero bytes of memory.
fn log(msg: &str) { // same as -> () println!("{msg}"); } let nothing = ();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
() // the type and the only value fn f() { } // returns () fn f() -> () { () } // the same, spelled out Result<(), E> // success without a payload
| Part | Description |
|---|---|
Type () |
Zero-sized. size_of::<()>() is 0. |
Value () |
The only inhabitant, so every () equals every other. |
Edge cases: an expression followed by ; becomes a statement and evaluates to (). A function whose last line has a stray semicolon, such as fn n() -> i32 { 5; }, fails with error E0308 (expected i32, found ()).
Usage notes
- Traits:
()implementsDebug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,HashandDefault. It also implementsFromIterator<()>, which is whycollect::<()>()works, andTermination, sofn main()may return it. Result<(), E>is the standard "may fail" return type. The?operator works on it just as with otherResulttypes.- Collecting
Result<(), E>from an iterator ofResult<(), E>stops at the first error, asvalidatedoes above. ifwithoutelsemust produce(); every branch of an expression-styleifmust have the same type.- Not the same as null. There is no null in safe Rust. Use
Option<T>for "maybe a value" and()for "no value at all". - Comparison with other languages: it plays the role of
void, but unlikevoidit is a real value that can be stored, passed and returned. - Mapping with
|_| ()discards a payload while keeping the success or failure:result.map(|_| ()). - Zero cost: generic code instantiated with
()produces no data for it;Vec<()>stores only a length.
Related
Tuples,! never type,Result<T, E>,The ? operator,Termination- Lessons: Tuples and unit, Result