Code Example Template
Deep-Dive System Documentation
Compound Primitives: Tuples and the Unit Type
Tuples and unit values are built-in compound types used to group values of different types without declaring a formal named struct.
1. Tuples (T1, T2, ...)
A tuple is a collection of values of different types. It has a fixed length; once declared, it cannot grow or shrink in size.
let packet: (u32, bool) = (0x02, true); // Groups a code and its status
2. The Unit Type ()
The unit type is a tuple with no elements. It is written as (). It has exactly one value, also written as ().
- Zero Sized Type (ZST): It occupies exactly 0 bytes in compiled assembly.
- Return Value: Functions or expressions that do not explicitly return a value return
()implicitly.
fn print_message() -> () {
println!("Hello"); // returns () implicitly
}
Core Operations
Because tuples are structural types rather than formally declared objects, they do not implement standard methods. In their place, Rust provides two primary operations:
tuple.N — Positional Accessing
Access individual tuple elements using . followed by their zero-indexed position.
let connection = (192, 168, 1, 100);
let first_octet = connection.0;
assert_eq!(first_octet, 192);
let (x, y) = tuple — Destructuring Pattern
Deconstruct a tuple into its constituent fields using a pattern-match assignment. Use _ to discard unwanted fields.
let result = (200, "OK", true);
let (status, _, is_success) = result;
assert_eq!(status, 200);
assert!(is_success);
Quick Reference Guide
let pair = (1, "ok");
assert_eq!(pair.0, 1);