Rust Structs

🦀 Rust Structs

Structs in Rust are used to group related data together into a single custom data type.

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.

struct User {
name: String,
age: u32,
active: bool,
}

✔ Similar to classes’ data part (but no inheritance)
✔ Fields have names and types


🔹 2. Creating a Struct Instance

fn main() {
let user1 = User {
name: String::from("Sanjit"),
age: 22,
active: true,
};

println!("{}", user1.name);
}


🔹 3. Mutable Structs

Structs are immutable by default.
Use mut to modify fields.

fn main() {
let mut user = User {
name: String::from("Amit"),
age: 25,
active: false,
};

user.active = true;
}

⚠️ You cannot make only one field mutable — the whole struct must be mut.


🔹 4. Struct Update Syntax

Reuse values from another struct.

let user2 = User {
name: String::from("Rahul"),
..user
};

✔ Copies remaining fields from user
⚠️ Ownership rules still apply (heap data may move)


🔹 5. Tuple Structs

Structs without named fields.

struct Color(i32, i32, i32);

let red = Color(255, 0, 0);
println!("{}", red.0);

✔ Useful when field names are not important


🔹 6. Unit-Like Structs

Structs with no fields.

struct Marker;

✔ Used for traits or type-level logic


🔹 7. Structs and Ownership

let u1 = User {
name: String::from("Rust"),
age: 10,
active: true,
};

let u2 = u1;

// println!("{}", u1.name); ❌ ownership moved
println!("{}", u2.name);

✔ Heap data (String) follows ownership rules
✔ Use references to avoid moves


🔹 8. Borrowing Struct Fields

fn print_name(user: &User) {
println!("{}", user.name);
}

✔ Borrows the struct
✔ Ownership stays with caller


🔹 9. Methods on Structs (impl Block)

Add behavior to structs using impl.

impl User {
fn is_active(&self) -> bool {
self.active
}
}

Calling method:

let user = User {
name: String::from("Sanjit"),
age: 22,
active: true,
};

println!("{}", user.is_active());


🔹 10. Methods with Mutable Reference

impl User {
fn deactivate(&mut self) {
self.active = false;
}
}

&self → read-only
&mut self → modify struct


🔹 11. Associated Functions (Like Static Methods)

impl User {
fn new(name: String, age: u32) -> User {
User {
name,
age,
active: true,
}
}
}

Usage:

let user = User::new(String::from("Rust"), 5);

🔹 12. Struct vs Tuple

FeatureStructTuple
Field names
ReadabilityHighLow
Use caseComplex dataSimple grouping

👉 Use structs when data has meaning.


❌ Common Mistakes

  • Forgetting mut for modification

  • Moving ownership unintentionally

  • Overusing tuples instead of structs

  • Not using impl for logic


🧠 Key Takeaways

  • Structs group related data

  • Fields have names and types

  • Ownership rules apply to fields

  • impl adds methods & behavior

  • Core foundation of Rust programs

You may also like...