Structs
Ek struct related values ko ek naam wale type ke neeche saath mein group karta hai. Ek tuple ke bar-aks, har field ka ek naam hota hai, jo use create aur istemal 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 baghair parhta hai — neeche rect.area(), rect ko consume kiye baghair width aur height parhta 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 ke aapne har ek ko handle kiya hai.
Practice Exercise
Ek struct Book define karein jiske fields title: String aur price: f64 hon. Ek method total(&self, quantity: u32) -> f64 add karein jo self.price * quantity as f64 wapas kare. title "Dune" aur price 15.0 wali ek Book banayein, phir book.total(3) print karein.