← Back to Rust Course | Chapter 5: Ownership | Lesson 5 of 6

Scope और Drop Trait

जब किसी value का usefulness का box (इसका scope) खत्म होता है, Rust अपने आप इसे आपके लिए साफ़ कर देता है -- पूछने की ज़रूरत नहीं।
Syntax
rust
{
    let name = value;
}  // name dropped here

drop(name);  // drop early

Automatic Cleanup at End of Scope

हर value के owner का एक scope है, और जब वह scope खत्म होता है, Rust अपने आप value के लिए cleanup code चलाता है, आपकी किसी explicit action के बिना किसी भी associated memory को free करते हुए।

उदाहरण: Automatic Cleanup at End of Scope

markup
fn main() {
    let message = String::from("cleaned up automatically");
    println!("{}", message);
} // message is dropped here

Implementing Drop

आप अपने custom struct के लिए Drop trait implement कर सकते हैं ताकि custom cleanup logic चले, जैसे एक message print करना, बिल्कुल तब जब उस type की एक value scope से बाहर जाती है।

उदाहरण: Implementing Drop

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

// Implement the `Drop` trait for `Connection`
impl Drop for Connection {
    // Define the function `drop` taking `self`
    fn drop(&mut self) {
        // Print "Closing connection: {}" to the console, substituting in `self.name` (with a trailing newline)
        println!("Closing connection: {}", self.name);
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `_conn`, set to `Connection { name: String::from("db") }`
    let _conn = Connection { name: String::from("db") };
    // Print "Using connection" to the console (with a trailing newline)
    println!("Using connection");
}

Drop Order Is Reverse of Declaration

जब कई values एक साथ scope से बाहर जाती हैं, Rust उन्हें declare होने के उल्टे order में drop करता है, एक stack को unwind करने जैसा।

उदाहरण: Drop Order Is Reverse of Declaration

markup
// Define a struct `Announcer` to group related fields together
struct Announcer(i32);

// Implement the `Drop` trait for `Announcer`
impl Drop for Announcer {
    // Define the function `drop` taking `self`
    fn drop(&mut self) {
        // Print "Dropping {}" to the console, substituting in `self.0` (with a trailing newline)
        println!("Dropping {}", self.0);
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `_first`, set to `Announcer(1)`
    let _first = Announcer(1);
    // Declare an immutable variable `_second`, set to `Announcer(2)`
    let _second = Announcer(2);
    // Print "Both created; watch the drop order below" to the console (with a trailing newline)
    println!("Both created; watch the drop order below");
}

Forcing an Early Drop

कभी-कभी आप चाहते हैं कि एक value अपने scope के naturally खत्म होने से पहले साफ़ हो जाए। चूंकि आप सीधे .drop() call नहीं कर सकते, standard library एक value को जल्दी consume और drop करने के लिए std::mem::drop प्रदान करती है।

उदाहरण: Forcing an Early Drop

markup
// Define a struct `Resource` to group related fields together
struct Resource;

// Implement the `Drop` trait for `Resource`
impl Drop for Resource {
    // Define the function `drop` taking `self`
    fn drop(&mut self) {
        // Print "Resource released early" to the console (with a trailing newline)
        println!("Resource released early");
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `res`, set to `Resource`
    let res = Resource;
    // Print "About to release early" to the console (with a trailing newline)
    println!("About to release early");
    drop(res);
    // Print "Released; rest of main continues" to the console (with a trailing newline)
    println!("Released; rest of main continues");
}
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. Rust के automatic Drop behavior पर भरोसा करने के बजाय हाथ से किसी value को free या साफ़ करने की कोशिश करना।
  2. यह मान लेना कि Drop variables बनने के order में चलता है -- यह असल में किसी scope के अंदर declaration के उल्टे order में चलता है।
  3. एक custom Drop implement करना और साथ ही अनावश्यक रूप से .clone() call करना, यह न समझते हुए कि Drop हर owned value पर अपने आप सिर्फ एक बार चलता है।
चैप्टर सारांश
  • जब किसी value का owner scope से बाहर जाता है, Rust इसे साफ़ करने के लिए अपने आप Drop trait का drop method call करता है।
  • Values को किसी scope के अंदर declare होने के उल्टे order में drop किया जाता है।
  • आप अपने खुद के types के लिए एक custom Drop implement कर सकते हैं ताकि cleanup code चले, जैसे एक resource बंद करना।
  • आप .drop() को हाथ से call नहीं कर सकते -- Rust double-free bugs से बचने के लिए इसे रोकता है; अगर ज़रूरत हो तो इसके बजाय std::mem::drop उपयोग करें।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.