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.