Structs
Ek struct related values ko ek naam wale type ke neeche saath mein group karta hai. Ek tuple ke ulat, har field ka ek naam hota hai, jo use create aur use karne wale code ko self-documenting bana deta hai.
struct Person {
name: String,
age: u32,
}
fn main() {
let alice = Person {
name: String::from("Alice"),
age: 30,
};
println!("{} is {} years old", alice.name, alice.age);
}Alice is 30 years old
impl ke sath methods
Ek impl block ek struct mein functions attach karta hai. Jo method &self leta hai woh us instance ko borrow karta hai jis par usko call kiya gaya hai, uske fields ko uski ownership liye bina padhta hai — neeche rect.area(), rect ko consume kiye bina width aur height padhta hai.
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());
}Area: 50
Aage: enums aur pattern matching — ek aisi value represent karna jo kai alag variants mein se ek ho, aur match ki yeh guarantee ki aapne har ek ko handle kiya hai.
Practice Exercise
Ek struct Book define karo jiske fields title: String aur price: f64 hon. Ek method total(&self, quantity: u32) -> f64 add karo jo self.price * quantity as f64 return kare. title "Dune" aur price 15.0 wali ek Book banao, phir book.total(3) print karo.