Tuple Structs
In this page:
Defining a Tuple Struct
A tuple struct combines the simplicity of a tuple with a distinct, named type. Fields have types but no names, declared in parentheses after the struct name.
Example: Defining a Tuple Struct
struct Point(i32, i32);
fn main() {
let p = Point(3, 4);
println!("({}, {})", p.0, p.1);
}
Login to try C/C++/Java/PHP code in the editor
Accessing Fields by Position
Because tuple struct fields have no names, you access them using dot notation with their zero-based index, just like a regular tuple.
Example: Accessing Fields by Position
struct Color(u8, u8, u8);
fn main() {
let red = Color(255, 0, 0);
println!("R:{} G:{} B:{}", red.0, red.1, red.2);
}
Login to try C/C++/Java/PHP code in the editor
Distinct Types Even With Same Shape
Two tuple structs wrapping the same underlying type are still completely distinct types to the compiler, which prevents accidentally mixing up conceptually different values, like meters and feet.
Example: Distinct Types Even With Same Shape
struct Meters(f64);
struct Feet(f64);
fn main() {
let distance = Meters(100.0);
println!("Distance: {} meters", distance.0);
}
Login to try C/C++/Java/PHP code in the editor
Unit Structs
A unit struct has no fields at all and is declared with just a name and a semicolon. It is used as a lightweight marker type, often to implement a trait without needing to store any data.
Example: Unit Structs
struct Marker;
fn main() {
let _m = Marker;
println!("Unit struct created with zero fields");
}
Login to try C/C++/Java/PHP code in the editor
- Trying to access tuple struct fields by name -- they are only accessible by position, like
.0and.1. - Confusing two different tuple structs with the same underlying field types, like
Meters(f64)andFeet(f64), which Rust treats as entirely distinct types. - Forgetting a unit struct (with no fields at all) is also valid syntax, used purely as a marker type.
- A tuple struct is declared like
struct Name(Type1, Type2);, with unnamed, positional fields. - Fields of a tuple struct are accessed using
.0,.1, and so on. - Even if two tuple structs wrap the same underlying type, they are distinct, incompatible types.
- A unit struct (
struct Marker;) has no fields at all and is used purely as a type-level marker.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: