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

Deref Trait का उपयोग

Deref एक wrapper type को सिखाता है कि इसके रखे value की तरह कैसे act करना है, ताकि आप इसे लगभग ऐसे उपयोग कर सकें जैसे यह wrapped ही न हो।
Syntax
rust
impl Deref for Name {
    type Target = Inner;

    fn deref(&self) -> &Self::Target {
        &self.field
    }
}

Box Already Implements Deref

Box<T> Deref implement करता है, यही कारण है कि *boxed_value आपको सीधे inner value देता है, भले ही Box खुद एक distinct type है।

उदाहरण: Box Already Implements Deref

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `boxed`, set to `Box::new(5)`
    let boxed = Box::new(5);
    // Print "Dereferenced: {}" to the console, substituting in `*boxed` (with a trailing newline)
    println!("Dereferenced: {}", *boxed);
}

Implementing Deref for a Custom Wrapper

आप अपने खुद के wrapper struct के लिए Deref implement कर सकते हैं, यह define करते हुए कि *wrapper को क्या produce करना चाहिए और method calls के लिए deref coercion enable करते हुए।

उदाहरण: Implementing Deref for a Custom Wrapper

markup
// Bring `std::ops::Deref` into scope
use std::ops::Deref;

// Define a struct `MyBox` to group related fields together
struct MyBox<T>(T);

// Implement the `Deref` trait for `MyBox`
impl<T> Deref for MyBox<T> {
    type Target = T;
    // Define the function `deref` taking `&self` and returning a `&T`
    fn deref(&self) -> &T {
        &self.0
    }
}

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

Deref Coercion in Method Calls

किसी method को call करते समय, Rust अपने आप deref coercion apply करता है, &MyBox<String> को ज़रूरत के अनुसार &str में convert करते हुए, ताकि आप wrapper पर सीधे String/str methods call कर सकें।

उदाहरण: Deref Coercion in Method Calls

markup
// Bring `std::ops::Deref` into scope
use std::ops::Deref;

// Define a struct `MyBox` to group related fields together
struct MyBox<T>(T);

// Implement the `Deref` trait for `MyBox`
impl<T> Deref for MyBox<T> {
    type Target = T;
    // Define the function `deref` taking `&self` and returning a `&T`
    fn deref(&self) -> &T {
        &self.0
    }
}

// Define the function `print_len` taking `s`
fn print_len(s: &str) {
    // Print "Length: {}" to the console, substituting in `s.len()` (with a trailing newline)
    println!("Length: {}", s.len());
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `wrapped`, set to `MyBox(String::from("coerced"))`
    let wrapped = MyBox(String::from("coerced"));
    print_len(&wrapped);
}

DerefMut for Mutable Access

Deref के साथ DerefMut implement करना wrapper type के ज़रिए mutable dereferencing (*wrapper = ... या &mut self methods call करना) भी allow करता है।

उदाहरण: DerefMut for Mutable Access

markup
// Bring `std::ops::{Deref, DerefMut}` into scope
use std::ops::{Deref, DerefMut};

// Define a struct `MyBox` to group related fields together
struct MyBox<T>(T);

// Implement the `Deref` trait for `MyBox`
impl<T> Deref for MyBox<T> {
    type Target = T;
    // Define the function `deref` taking `&self` and returning a `&T { &self.0 }`
    fn deref(&self) -> &T { &self.0 }
}

// Implement the `DerefMut` trait for `MyBox`
impl<T> DerefMut for MyBox<T> {
    // Define the function `deref_mut` taking `self` and returning a `&mut T { &mut self.0 }`
    fn deref_mut(&mut self) -> &mut T { &mut self.0 }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `wrapped`, initialized to `MyBox(10)`
    let mut wrapped = MyBox(10);
    *wrapped += 5;
    // Print "{}" to the console, substituting in `*wrapped` (with a trailing newline)
    println!("{}", *wrapped);
}
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. यह भूल जाना कि Deref सिर्फ *value और method calls के behave करने के तरीके को प्रभावित करता है -- यह wrapper की खुद की type identity नहीं बदलता।
  2. यह मान लेना कि Deref implement करना आपको अपने आप DerefMut भी देता है -- mutable dereferencing को एक अलग trait implementation चाहिए।
  3. Inheritance-जैसे behavior fake करने के लिए custom Deref implementations overuse करना, जो code को follow करने में confusing बना सकता है।
चैप्टर सारांश
  • Deref implement करना एक custom type को * से dereferenced होने देता है, Box<T> के काम करने के तरीके जैसा।
  • Deref coercion methods call करते समय अपने आप &MyType को &InnerType में convert करता है, manual dereferencing घटाते हुए।
  • DerefMut mutable dereferencing के लिए corresponding trait है और इसे अलग से implement किया जाना चाहिए।
  • Deref वही है जो Box, Rc, और custom wrapper types जैसे smart pointers को लगभग उनके inner value की तरह उपयोग होने देता है।
🔒

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.