Open Menu

    Rust Structs - Normal, Tuple, and Unit-Like

    Flavio Del Grosso

    Flavio Del GrossoJan 25, 2024

    4 min read1022 words

    Rust, with its emphasis on safety and performance, offers THREE distinct types of structs! Understanding each type is important for organizing and managing data in your Rust programs. In this article, we'll delve into each type of struct, exploring their unique characteristics and use cases.

    1. Normal (Classic) Structs

    Normal structs are the cornerstone of Rust's data structuring capabilities. They allow you to define named collections of related data, organized into fields. This classic approach to structuring data provides versatility, readability, and maintainability, making it ideal for complex data structures.

    rust

    struct Person {
        name: String,
        age: u32,
        email: String,
    }

    In the example above, Person is a classic struct with fields for name, age, and email, encapsulating related data into a single entity.

    2. Tuple Structs

    Tuple structs offer a blend of simplicity and clarity by combining the concise syntax of tuples with the naming conventions of structs. They are useful when you need a lightweight structure without the verbosity of named fields.

    rust

    struct Point(f64, f64);

    In this example, Point is a tuple struct representing a point in 2D space, defined by its x and y coordinates.

    3. Unit-like Structs

    Unit-like structs are the minimalist option in Rust's struct ecosystem. They have no fields and are particularly handy for scenarios involving generics or marker traits.

    rust

    struct EmptyStruct;

    EmptyStruct is a unit-like struct with no fields. Despite their simplicity, they offer significant benefits in terms of type safety, memory optimization, and code organization.

    Conclusion

    Rust's three types of structs—normal, tuple, and unit-like—offer a diverse toolkit for organizing and managing data. Whether you prioritize clarity, simplicity, or efficiency, Rust's struct system provides the flexibility and power needed to build robust and maintainable software.


    Share on