Rust Structs
🦀 Rust Structs
They are one of the most important building blocks in Rust and are heavily used with ownership, borrowing, and methods.
🔹 1. What Is a Struct?
A struct lets you define a custom data type with named fields.
✔ Similar to classes’ data part (but no inheritance)
✔ Fields have names and types
🔹 2. Creating a Struct Instance
🔹 3. Mutable Structs
Structs are immutable by default.
Use mut to modify fields.
⚠️ You cannot make only one field mutable — the whole struct must be mut.
🔹 4. Struct Update Syntax
Reuse values from another struct.
✔ Copies remaining fields from user
⚠️ Ownership rules still apply (heap data may move)
🔹 5. Tuple Structs
Structs without named fields.
✔ Useful when field names are not important
🔹 6. Unit-Like Structs
Structs with no fields.
✔ Used for traits or type-level logic
🔹 7. Structs and Ownership
✔ Heap data (String) follows ownership rules
✔ Use references to avoid moves
🔹 8. Borrowing Struct Fields
✔ Borrows the struct
✔ Ownership stays with caller
🔹 9. Methods on Structs (impl Block)
Add behavior to structs using impl.
Calling method:
🔹 10. Methods with Mutable Reference
✔ &self → read-only
✔ &mut self → modify struct
🔹 11. Associated Functions (Like Static Methods)
Usage:
🔹 12. Struct vs Tuple
| Feature | Struct | Tuple |
|---|---|---|
| Field names | ✔ | ❌ |
| Readability | High | Low |
| Use case | Complex data | Simple grouping |
👉 Use structs when data has meaning.
❌ Common Mistakes
Forgetting
mutfor modificationMoving ownership unintentionally
Overusing tuples instead of structs
Not using
implfor logic
🧠 Key Takeaways
Structs group related data
Fields have names and types
Ownership rules apply to fields
impladds methods & behaviorCore foundation of Rust programs
