← Back to Rust Course | Chapter 7: Structs | Lesson 7 of 7

Tuple Structs

A tuple struct gives a name to a group of values without bothering to name each one individually.

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

markup
struct Point(i32, i32);

fn main() {
    let p = Point(3, 4);
    println!("({}, {})", p.0, p.1);
}

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

markup
struct Color(u8, u8, u8);

fn main() {
    let red = Color(255, 0, 0);
    println!("R:{} G:{} B:{}", red.0, red.1, red.2);
}

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

markup
struct Meters(f64);
struct Feet(f64);

fn main() {
    let distance = Meters(100.0);
    println!("Distance: {} meters", distance.0);
}

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

markup
struct Marker;

fn main() {
    let _m = Marker;
    println!("Unit struct created with zero fields");
}
Common Mistakes
  1. Trying to access tuple struct fields by name -- they are only accessible by position, like .0 and .1.
  2. Confusing two different tuple structs with the same underlying field types, like Meters(f64) and Feet(f64), which Rust treats as entirely distinct types.
  3. Forgetting a unit struct (with no fields at all) is also valid syntax, used purely as a marker type.
Chapter Summary
  • 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.