Course contentsShow
← Rust
Lesson 490 of 1,9105. Type System and TraitsFree lesson

Tuple Structs vs Named Field Structs

Select the correct data structure representation based on the encapsulation requirements of your domain.

In this lesson, you will learn how to choose between tuple structs and named field structs to best model your data based on encapsulation and readability.

In Rust, choosing the right struct representation isn't just about syntax—it’s about communicating intent and enforcing safety boundaries.

Named Field Structs

Named field structs are the "standard" way to define data. By giving every field a name, you create self-documenting code. They are the best choice when a type has multiple distinct pieces of data that shouldn't be confused with one another.

struct User {
    username: String,
    email: String,
    age: u8,
}

Using this approach makes the code readable and allows you to construct the struct easily even if you reorder the fields in the definition.

Tuple Structs

Tuple structs are defined by the types of their fields rather than their names. They are often used as "Newtype" wrappers to add type safety to primitive values, or for simple groups of data where the names are obvious (like Point(f64, f64)).

struct Email(String);
struct Username(String);

fn send_email(email: Email) { /* ... */ }

Here, using Email(String) instead of a raw String prevents you from accidentally passing a Username into a function that expects an Email. The compiler will catch that mistake, even though the underlying data is identical.

Choosing the Right Tool

The decision comes down to encapsulation requirements:

  1. Use Named Field Structs when you need to maintain field-level visibility (e.g., pub vs private fields) or when the semantic meaning of each field is essential for the API consumer to know.
  2. Use Tuple Structs when you want to treat a value as a distinct type but don't need to expose internal labels. They are perfect for small, cohesive units where the order is fixed and the domain meaning is clear.

If your struct requires five or more fields, or if any field might be confused with another of the same type (like two u32 values representing width and height), always default to a named field struct to avoid "argument soup" bugs.

Key Takeaway: Use named field structs for clarity and public APIs, and use tuple structs to create lightweight, type-safe wrappers around primitive data.