Rust Data Structures: Tuples, Structs, and Tuple Structs

Rust provides three alternatives for handling multiple values of different types: tuples, structs, and tuple structs. These data structures differ in their characteristics and use cases.

Differences Between Tuples and Tuple Structs

Tuple structs occupy a middle ground between tuples and structs, offering named types with anonymous fields. The main differences between tuples and tuple structs are:

    • Privacy**: Elements of a tuple struct are private by default and cannot be accessed outside the module they’re defined in.

  • Type distinction**: Tuple structs define a type, so two tuple structs with fields of the same type are considered two different types.

  • Attributes**: Tuple structs can have attributes such as #[must_use] or #[derive(...)].

  • Function-like behavior**: Tuple structs implement the Fn* family by default, allowing them to be invoked like functions or passed as parameters to higher-order functions.

  • Struct update syntax**: Tuple structs support the struct update syntax, simplifying the creation of a new instance of a struct where most values are equal to another instance of the same struct.

Use Cases for Each Alternative

The choice of data structure depends on the specific use case:

    • Tuples**: When the name of the type carries semantic information, and having names would likely be overkill.

  • Structs**: When there’s more than one field, and having names helps read the code.

  • Tuple structs**: When you want to use types to further enhance the clarity of your code, and having names is not necessary.


// Example of a tuple
let person = ("John", 30);

// Example of a struct
struct Person {
    name: String,
    age: u8,
}
let person = Person { name: "John".to_string(), age: 30 };

// Example of a tuple struct
struct Person(String, u8);
let person = Person("John".to_string(), 30);

Ultimately, the choice between tuples, structs, and tuple structs depends on how they impact the readability and maintainability of your code.

Leave a Reply