Structs in Rust
Table of Contents
Structs in Rust
In Rust, structs (structures) are custom data types that allow you to group related pieces of data together. Unlike tuples, which group values without naming them, structs allow you to name each piece of data, making your code more organized, readable, and maintainable. Structs are a fundamental building block for creating more complex data structures and represent the "product type" in Functional Programming terms (an instance has all its defined fields).
Types of Structs in Rust
Rust offers three kinds of structs:
. Classic Structs (Named-Field Structs)
- Description: The most common type of struct, where each piece of data (called a "field") has a name and a type. This provides clear semantics and easy access to individual fields.
Definition Syntax:
struct User { active: bool, username: String, email: String, sign_in_count: u64, }Instantiation:
let user1 = User { active: true, username: String::from("alice123"), email: String::from("alice@example.com"), sign_in_count: 1, };Accessing Fields: Use dot notation (
.) to access fields.println!("Username: {}", user1.username);Mutability: If the struct instance is declared
mut, its fields can be changed.let mut user2 = User { /* ... */ }; user2.email = String::from("bob@example.com");Field Init Shorthand: If a variable name is the same as a struct field name, you can omit the colon and value.
let username = String::from("charlie"); let user3 = User { username, // shorthand for username: username active: true, email: String::from("charlie@example.com"), sign_in_count: 1, };Struct Update Syntax: Easily create a new struct instance from an existing one, overriding only specific fields.
let user4 = User { email: String::from("david@example.com"), ..user1 // Fills in remaining fields from user1 };
2. Tuple Structs
- Description: Similar to regular tuples but with a name, giving semantic meaning to the collection of values. Fields are unnamed and accessed by index. Useful when you want to give a tuple a specific type name.
Definition Syntax:
struct Color(i32, i32, i32); // Represents an RGB color struct Point(i32, i32, i32); // Represents a 3D point
Instantiation:
let black = Color(0, 0, 0); let origin = Point(0, 0, 0);
Accessing Fields: Use dot notation with the index (
.0,.1, etc.).println!("Black R: {}", black.0);- Type Distinction: Two tuple structs with the same field types are still considered different types because of their distinct names.
Color(0,0,0)is aColor, not aPoint.
3. Unit-Like Structs
- Description: Structs that have no fields. They are primarily used when you need to implement a trait on some type but don't have any data to store in the type itself. They behave somewhat like an empty
()tuple. Definition Syntax:
struct AlwaysEqual;
Instantiation:
let subject = AlwaysEqual;
impl Blocks (Implementing Methods)
Structs often have associated functions and methods (functions that belong to the struct). These are defined in an impl (implementation) block.
Methods: Functions that are defined within an
implblock and whose first parameter is&self,&mut self, orself(referring to the instance of the struct).impl User { // Method that takes an immutable reference to self fn get_domain(&self) -> String { self.email.split('@').nth(1).unwrap_or("").to_string() } // Method that takes a mutable reference to self fn increment_sign_in_count(&mut self) { self.sign_in_count += 1; } // Method that takes ownership of self (consumes the struct) fn into_username(self) -> String { self.username } }Associated Functions: Functions defined within an
implblock that do not takeselfas their first parameter. They are often used as constructors.impl User { // Associated function (constructor) fn new(username: String, email: String) -> User { User { active: true, username, email, sign_in_count: 1, } } } // Call associated function: let new_user = User::new(String::from("frank"), String::from("frank@example.com"));
Relationship with Traits
Structs are the primary types that implement traits, enabling them to share behavior and participate in polymorphism. You use an impl Trait for Struct block to define how a specific struct adheres to a given trait's contract.
Memory Layout
By default, Rust does not guarantee the specific memory layout of struct fields (#[repr(Rust)]). The compiler is free to reorder fields to optimize for size (by reducing padding) or alignment. If you need a specific memory layout (e.g., for FFI with C), you can use #[repr(C)] to force a C-compatible layout.
When to Use Structs
- When you have related data that you want to group together.
- When each piece of data has a clear, descriptive name.
- When you want to define methods that operate on this grouped data.
- When you need to create custom types that differentiate from other types even if they have similar internal structure (e.g.,
Colorvs.Point).