Customize the Deref trait or dereferencing operator * for the type &MyType

Here is my code snippet:

use std::ops::Deref;

fn main()
{
    let a = MyBox(90);
    let r_a = &a;
    println!("*a returns {}",*a);
    println!("*(&MyBox<i32>) returns: {:?}", *r_a);
    
}

#[derive(Debug)]
struct MyBox<T>(T);


impl<T> Deref for MyBox<T>
{
    type Target = T;
    fn deref(&self) -> &Self::Target 
    {
        &self.0 
    }
}

So *a returns 90 but the *r_a returns MyBox(90). However, I want *r_a to return 90 only like *a. So the Deref trait needs to be implemented for the type &MyBox<T>. Here is my attempt at Deref implementation for &MyBox<T>:

impl<T> Deref for &MyBox<T>
{
    type Target = T;
    fn deref(&self) -> &T 
    {
        *self
    }
}

The compiler shows an error like:

   Compiling playground v0.0.1 (/playground)
error[E0119]: conflicting implementations of trait `Deref` for type `&MyBox<_>`
  --> src/main.rs:31:1
   |
31 | impl<T> Deref for &MyBox<T>
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: conflicting implementation in crate `core`:
           - impl<T> Deref for &T
             where T: ?Sized;

I understand that Rust standard has default Deref implementation for &T --&MyBox(T)-- hence it shows an error.

Using the AsRef or my custom trait I am able to return 90 from the type &MyBox<T> but that would be without using the dereferencing operator *.

Any ideas on how to customize the dereferencing operator * so that it returns 90 from the type &MyBox<T>?

Thanks,
Yousuf.

You can't, dereferencing a reference always gives you a place of the referenced type, you can't override this.

5 Likes

Which is the case because of the generic trait implementation I've linked in your other topic and the fact that Rust doesn't support specialization, prohibiting you from implementing one trait multiple times for a single type.

2 Likes

Plus the fact that * on &_ doesn't actually use Deref (see my post in the other thread).

4 Likes