Why implement a trait for a reference if all the trait methods already take a reference to self?

Hello. I am using the embedded-hal-async crate and I was surfing the source code of it when I faced an implementation of a trait for a reference of a type implementing this trait, that is: impl<T: Trait> Trait for &mut T.

I understand why this sometimes can be useful. For example, it can be used when the trait methods consume the object, but you still want the trait to be implemented somehow for the reference of this object.

But what if all the methods of the trait already take a reference, specifically a mutable reference?
What is the point of such impl for &mut T?

That's exactly what I see in the source of of embedded-hal-async crate. Here is the link.

All the methods of the trait SpiDevice take &mut self. So having a mutable reference to a type implementing SpiDevice trait already allows me to call the methods of the trait.
However, further you see an implementation of the trait SpiDevice for mutable references to types implementing trait SpiDevice (impl<Word: Copy + 'static, T: SpiDevice<Word> + ?Sized> SpiDevice<Word> for &mut T ), where all the implemented methods just call the methods of the implementation for T.
Why is this done? How this can be useful?


You'd have to ask library authors, but it likely has to do with allowing you to pass both an owned device, and a reference to the same generic function.

1 Like

The ?Sized part is also important, because it allows you to pass &mut dyn Trait in places that take an impl Trait parameter.


It's almost always generics. These seemingly tautological impls make life more convenient in a generic context.

For example, there's an impl<T> From<T> for T in std. You would never actually write let x: i32 = i32::from(42_i32); yourself, but it is nice to be able to pass an i32, an i16 or an i8 where an Into<i32> is required.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.