← Back to Rust Course | Chapter 7: Structs | Lesson 3 of 7

Methods और self

Methods वे actions हैं जो एक struct कर सकता है, और self बस यह है कि method कैसे उस struct को refer करता है जिससे यह attached है।
Syntax
rust
impl Name {
    fn read(&self) {}
    fn modify(&mut self) {}
    fn consume(self) {}
}

Reading Data with &self

एक method जिसे सिर्फ struct की fields पढ़नी हैं वह &self लेता है, instance का एक immutable borrow। यह सबसे आम तरह का method है।

उदाहरण: Reading Data with &self

markup
// Define a struct `Book` to group related fields together
struct Book {
    title: String,
    pages: u32,
}

// Implement methods on `Book`
impl Book {
    // Define the function `summary` taking `&self` and returning a String
    fn summary(&self) -> String {
        format!("{} ({} pages)", self.title, self.pages)
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `book`, set to `Book { title: String::from("The Rust Book"), pages: 500 }`
    let book = Book { title: String::from("The Rust Book"), pages: 500 };
    // Print "{}" to the console, substituting in `book.summary()` (with a trailing newline)
    println!("{}", book.summary());
}

Modifying Data with &mut self

एक method जो struct की किसी field को बदलता है उसे &mut self लेना चाहिए, एक mutable borrow, और instance रखने वाले variable को खुद mut declare किया जाना चाहिए।

उदाहरण: Modifying Data with &mut self

markup
// Define a struct `Counter` to group related fields together
struct Counter {
    value: i32,
}

// Implement methods on `Counter`
impl Counter {
    // Define the function `increment` taking `self`
    fn increment(&mut self) {
        self.value += 1;
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `counter`, initialized to `Counter { value: 0 }`
    let mut counter = Counter { value: 0 };
    counter.increment();
    counter.increment();
    // Print "Counter: {}" to the console, substituting in `counter.value` (with a trailing newline)
    println!("Counter: {}", counter.value);
}

Consuming self

एक method जो plain self (बिना & के) लेता है instance की पूरी ownership लेता है, इसे consume करते हुए। यह तब उपयोग होता है जब एक method किसी value को किसी और चीज़ में transform करता है और original को और उपयोग नहीं होना चाहिए।

उदाहरण: Consuming self

markup
// Define a struct `Wrapper` to group related fields together
struct Wrapper {
    value: String,
}

// Implement methods on `Wrapper`
impl Wrapper {
    // Define the function `unwrap` taking `self` and returning a String
    fn unwrap(self) -> String {
        self.value
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `wrapped`, set to `Wrapper { value: String::from("inside") }`
    let wrapped = Wrapper { value: String::from("inside") };
    // Declare an immutable variable `inner`, set to `wrapped.unwrap()`
    let inner = wrapped.unwrap();
    // Print "{}" to the console, substituting in `inner` (with a trailing newline)
    println!("{}", inner);
}

Dot Syntax Handles Referencing Automatically

जब आप instance.method() call करते हैं, Rust अपने आप referencing या dereferencing की सही मात्रा insert करता है ताकि method के self parameter की उम्मीद से मेल खाए, इसलिए आपको शायद ही कभी (&instance).method() हाथ से लिखना पड़े।

उदाहरण: Dot Syntax Handles Referencing Automatically

markup
// Define a struct `Temperature` to group related fields together
struct Temperature {
    celsius: f64,
}

// Implement methods on `Temperature`
impl Temperature {
    // Define the function `to_fahrenheit` taking `&self` and returning a floating-point number
    fn to_fahrenheit(&self) -> f64 {
        self.celsius * 9.0 / 5.0 + 32.0
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `temp`, set to `Temperature { celsius: 20.0 }`
    let temp = Temperature { celsius: 20.0 };
    // Print "{}F" to the console, substituting in `temp.to_fahrenheit()` (with a trailing newline)
    println!("{}F", temp.to_fahrenheit());
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. &self का मतलब होने पर self लिखना, जो struct को method में move कर देगा बजाय इसे सिर्फ borrow करने के।
  2. यह भूल जाना कि &mut self किसी भी method के लिए ज़रूरी है जो struct की अपनी किसी field को modify करता है।
  3. किसी method को Type::method(instance) के रूप में call करना जब simpler instance.method() dot-call syntax ज़्यादा clear और idiomatic है।
चैप्टर सारांश
  • &self instance को immutably borrow करता है, एक method को अपनी fields पढ़ने देते हुए बिना ownership लिए।
  • &mut self instance को mutably borrow करता है, एक method को अपनी fields modify करने देते हुए।
  • Plain self (बिना & के) instance की ownership लेता है, इसे consume करते हुए -- कम बार उपयोग होता है, आमतौर पर conversions के लिए।
  • Dot-call syntax instance.method() अपने आप self के लिए referencing/dereferencing handle करता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.