Struct, Enum और Trait
Rust Methods and impl Blocks
Attach behavior to a struct: methods with &self, changes with &mut self and constructors like new.
आप क्या सीखेंगे
- impl blocks
- &self and &mut self
- Associated functions
Receiver → what the method can do
fn area(&self)readfn scale(&mut self, f)changefn new(w, h) -> SelfcreateFunctions that belong to a type
An impl block holds the functions that belong to a type. A method takes self as its first parameter and is called with a dot. A function without self, such as new, is called with the type name and ::.
&self borrows the rectangle for reading and &mut self borrows it for changing, which is why rect must be mut to call scale. Self is a short name for the type of the impl block. new and square are associated functions used as constructors.
मुख्य बातें
- &self reads the value.
- &mut self changes it.
Rectangle::newhas no self: it is a constructor.
चलने योग्य Rust उदाहरण
Rust
main.rs
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
fn new(width: f64, height: f64) -> Self {
Self { width, height }
}
fn square(size: f64) -> Self {
Self::new(size, size)
}
fn area(&self) -> f64 {
self.width * self.height
}
fn scale(&mut self, factor: f64) {
self.width *= factor;
self.height *= factor;
}
}
fn main() {
let mut rect = Rectangle::new(3.0, 4.0);
println!("area: {}", rect.area());
rect.scale(2.0);
println!("scaled: {} x {} = {}", rect.width, rect.height, rect.area());
println!("square: {}", Rectangle::square(5.0).area());
}
area: 12
scaled: 6 x 8 = 48
square: 25अभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- बैंक खाते के नियम जमा और निकासी के नियमों के पीछे खाते के balance की सुरक्षा करें, और अमान्य operations को अस्वीकार करें। आसान
- Distance Between Points Compute the straight-line distance between two points. आसान