← Back to Rust Course | Chapter 13: Smart Pointers & Unsafe | Lesson 5 of 7

Drop Trait का उपयोग

Drop एक special goodbye method है जिसे Rust किसी value के हमेशा के लिए गायब होने से ठीक पहले अपने आप call करता है।
Syntax
rust
impl Drop for Name {
    fn drop(&mut self) {
        // cleanup
    }
}

Implementing Drop

Drop trait का drop method implement करना किसी type को इसकी value का scope खत्म होते ही अपने आप custom cleanup code execute करने देता है।

उदाहरण: Implementing Drop

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

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

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `_logger`, set to `Logger { name: String::from("main-logger") }`
    let _logger = Logger { name: String::from("main-logger") };
    // Print "Logger is active" to the console (with a trailing newline)
    println!("Logger is active");
}

Forcing an Early Drop

चूंकि सीधे .drop() call करना compiler द्वारा disallowed है, std::mem::drop(value) का उपयोग किसी value को इसके natural scope के खत्म होने से पहले साफ़ कराने के लिए किया जाता है।

उदाहरण: 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 cleaned up" to the console (with a trailing newline)
        println!("Resource cleaned up");
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `res`, set to `Resource`
    let res = Resource;
    // Print "About to drop early" to the console (with a trailing newline)
    println!("About to drop early");
    drop(res);
    // Print "Dropped; continuing" to the console (with a trailing newline)
    println!("Dropped; continuing");
}

Drop Order Matches Reverse Declaration

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

उदाहरण: Drop Order Matches Reverse Declaration

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

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

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `_a`, set to `Item(1)`
    let _a = Item(1);
    // Declare an immutable variable `_b`, set to `Item(2)`
    let _b = Item(2);
    // Declare an immutable variable `_c`, set to `Item(3)`
    let _c = Item(3);
    // Print "All items created" to the console (with a trailing newline)
    println!("All items created");
}

A Practical Use: Resource Cleanup

Drop आमतौर पर यह गारंटी देने के लिए उपयोग होता है कि cleanup logic, जैसे एक connection बंद करना, हमेशा चले -- भले ही function जल्दी return हो -- क्योंकि value जब भी इसका scope खत्म हो, drop हो जाती है।

उदाहरण: A Practical Use: Resource Cleanup

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

// 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.id` (with a trailing newline)
        println!("Closing connection #{}", self.id);
    }
}

// Define the function `use_connection` with no parameters
fn use_connection() {
    // Declare an immutable variable `_conn`, set to `Connection { id: 7 }`
    let _conn = Connection { id: 7 };
    // Print "Using connection #7" to the console (with a trailing newline)
    println!("Using connection #7");
}

// Entry point: execution of the program starts here
fn main() {
    use_connection();
    // Print "Connection was closed automatically" to the console (with a trailing newline)
    println!("Connection was closed automatically");
}
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. किसी value पर सीधे .drop() call करने की कोशिश करना -- Rust इसे explicitly मना करता है और इसके बजाय std::mem::drop प्रदान करता है।
  2. यह मान लेना कि Drop::drop किसी value के move होते ही तुरंत चलता है -- यह सिर्फ तब चलता है जब value का owner सच में scope से बाहर जाता है।
  3. यह भूल जाना कि values उसी scope के अंदर declaration के उल्टे order में drop होती हैं, जो cleanup ordering के लिए मायने रख सकता है।
चैप्टर सारांश
  • Drop implement करना किसी type को इसकी value scope से बाहर जाने पर अपने आप custom cleanup logic चलाने देता है।
  • आप drop method सीधे call नहीं कर सकते; एक early drop मजबूर करने के लिए free function std::mem::drop(value) उपयोग करें।
  • Values किसी scope के अंदर उनकी declaration के उल्टे order में drop होती हैं।
  • Drop आमतौर पर file handles, locks, या network connections जैसे resources release करने के लिए उपयोग होता है।
🔒

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.