Rust Data Structures
Estimated reading: 3 minutes 30 views

🦀 Rust – Structs: Define and Use Custom Data Types Safely

🧲 Introduction – Why Learn Structs in Rust?

Structs in Rust let you define your own data types using named fields. They are perfect for modeling complex entities like users, books, or configurations. Rust’s structs are powerful, safe, and tightly integrated with ownership and borrowing systems.

🎯 In this guide, you’ll learn:

  • How to define, instantiate, and use structs
  • How ownership and borrowing work with struct fields
  • How to use impl blocks for methods
  • Real examples with output and line-by-line explanations

📦 Defining and Instantiating a Struct

🔹 Code Example:

struct User {
    username: String,
    age: u32,
}

fn main() {
    let user1 = User {
        username: String::from("Alice"),
        age: 28,
    };

    println!("{} is {} years old.", user1.username, user1.age);
}

🧠 Explanation:

  • struct User defines a custom type with String and u32 fields.
  • Struct fields are accessed using dot notation.
  • Ownership of String::from("Alice") is moved into the struct.

📤 Output:

Alice is 28 years old.

🛠️ Updating Structs with Struct Update Syntax

🔹 Code Example:

struct User {
    username: String,
    age: u32,
}

fn main() {
    let user1 = User {
        username: String::from("Bob"),
        age: 35,
    };

    let user2 = User {
        username: String::from("Charlie"),
        ..user1
    };

    println!("user2: {} {}", user2.username, user2.age);
}

🧠 Explanation:

  • ..user1 copies the remaining fields from user1.
  • user1’s ownership is partially moved—fields like username can’t be reused after.

📤 Output:

user2: Charlie 35

🎯 Implementing Methods with impl

🔹 Code Example:

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle {
        width: 10,
        height: 5,
    };

    println!("Area: {}", rect.area());
}

🧠 Explanation:

  • impl Rectangle defines a method on the struct.
  • &self borrows the instance immutably.
  • rect.area() calls the method just like OOP style.

📤 Output:

Area: 50

🔁 Associated Functions (Constructors)

🔹 Code Example:

struct Color {
    red: u8,
    green: u8,
    blue: u8,
}

impl Color {
    fn new(red: u8, green: u8, blue: u8) -> Self {
        Self { red, green, blue }
    }
}

fn main() {
    let blue = Color::new(0, 0, 255);
    println!("Blue RGB: {}, {}, {}", blue.red, blue.green, blue.blue);
}

🧠 Explanation:

  • Self refers to the current struct type.
  • Color::new(...) acts like a constructor.

📤 Output:

Blue RGB: 0, 0, 255

🧩 Tuple Structs

🔹 Code Example:

struct Point(i32, i32);

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

🧠 Explanation:

  • Tuple structs are unnamed fields but typed.
  • Access via index just like tuples.

📤 Output:

(0, 0)

📋 Unit-like Structs

🔹 Code Example:

struct Marker;

fn main() {
    let _m = Marker;
}

🧠 Explanation:

  • Zero-sized struct (useful for traits or type markers)

⚠️ Common Struct Mistakes

MistakeError MessageFix
Field not initialized“missing field”Initialize all fields or use ..
Using moved fields“value used after move”Clone if reuse is needed
Accessing private fields“field is private”Mark field pub if used outside

📌 Summary – Recap & Next Steps

Structs in Rust provide a clear and type-safe way to model real-world entities. With support for methods, pattern matching, and ownership-aware behavior, they are a core part of idiomatic Rust.

🔍 Key Takeaways:

  • Use struct to define custom types with named fields
  • Access fields using dot notation; move or borrow as needed
  • Use impl to attach methods and constructors
  • Tuple and unit-like structs offer alternate struct styles

⚙️ Next: Explore Rust – Enums to model state and data variants effectively.


❓FAQs


Can a struct have fields of different types in Rust?
✅ Yes. Each field can be a completely different type.


Can I define methods for structs?
✅ Absolutely! Use impl StructName { fn method(&self) {...} }.


What’s the difference between struct and tuple struct?
✅ Structs use named fields. Tuple structs use positional fields and are accessed with .0, .1, etc.


Can I return a struct from a function?
✅ Yes, just return the struct or use Self in an impl.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Rust – Structs

Or Copy Link

CONTENTS
Scroll to Top