Rust Structs
Custom data types for organizing related data
🏗️ What are Structs?
Structs are custom data types that group related values together. They're like blueprints for creating objects with named fields, making your code more organized and readable.
struct Person {
name: String,
age: u32,
email: String,
}
Types of Structs
Named Fields
Structs with named fields
struct User {
name: String,
age: u32,
}
Tuple Structs
Structs without named fields
struct Color(i32, i32, i32);
Methods
Functions associated with structs
impl User {
fn greet(&self) {}
}
Associated Functions
Constructor-like functions
impl User {
fn new() -> User {}
}
🔹 Creating and Using Structs
Define a struct and create instances:
// Define a struct
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
// Create an instance
let rect = Rectangle {
width: 30,
height: 50,
};
// Access fields
println!("Width: {}", rect.width);
println!("Height: {}", rect.height);
// Calculate area
let area = rect.width * rect.height;
println!("Area: {}", area);
}
Output:
Width: 30
Height: 50
Area: 1500
Height: 50
Area: 1500
🔹 Struct Methods
Add functionality to structs using impl blocks:
struct Circle {
radius: f64,
}
impl Circle {
// Associated function (constructor)
fn new(radius: f64) -> Circle {
Circle { radius }
}
// Method that borrows self
fn area(&self) -> f64 {
3.14159 * self.radius * self.radius
}
// Method that takes ownership
fn grow(mut self, factor: f64) -> Circle {
self.radius *= factor;
self
}
}
fn main() {
let circle = Circle::new(5.0);
println!("Area: {:.2}", circle.area());
let bigger_circle = circle.grow(2.0);
println!("New area: {:.2}", bigger_circle.area());
}
Output:
Area: 78.54
New area: 314.16
New area: 314.16
🔹 Tuple Structs
Structs that look like tuples but have a name:
// Tuple structs
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
fn main() {
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
// Access by index
println!("Red component: {}", black.0);
println!("X coordinate: {}", origin.0);
// Destructure
let Color(r, g, b) = black;
println!("RGB: ({}, {}, {})", r, g, b);
}
Output:
Red component: 0
X coordinate: 0
RGB: (0, 0, 0)
X coordinate: 0
RGB: (0, 0, 0)
🔹 Struct Update Syntax
Create new instances based on existing ones:
struct User {
username: String,
email: String,
age: u32,
active: bool,
}
fn main() {
let user1 = User {
username: String::from("alice"),
email: String::from("[email protected]"),
age: 25,
active: true,
};
// Create user2 using user1's data
let user2 = User {
username: String::from("bob"),
email: String::from("[email protected]"),
..user1 // Use remaining fields from user1
};
println!("User2 age: {}", user2.age);
println!("User2 active: {}", user2.active);
}
Output:
User2 age: 25
User2 active: true
User2 active: true