What does implementing a trait on a mutable borrow of a struct mean?

I was reading an example listed in the Serde docs (Implementing a Deserializer) and I was puzzled by this line impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de>. I'm not sure I know how to read for &'a mut Deserializer<'de>.

I haven't seen this anywhere else. Any help deciphering this would be appreciated.


&mut Deserializer is a type just like Deserializer or u32 or whatever. You can implement traits for references just like you can implement traits for other types.

Thanks. But as a follow up question: if the function's receiver on such an implementation type just says self does it mean that it should really be read as &mut self?

A method receiver of self will have type Self -- which in this case is &mut Deserializer.

A method receiver of &mut self will have type &mut Self -- which in this case would have two layers of references &mut &mut Deserializer.

1 Like

Yes - Well, kind of, &T implements clone and so, it behaves like &mut self because self is itself a reference to T. If you were to change self to &mut self as @cuviper mentions, it would be two layers of references.

Sorry to nitpick, but I don't understand your point, and I don't want to spread any misconception. I'm not sure why you mention &T, or what Clone has to do with this.

You can never go from &T to &mut T, and the latter doesn't implement Clone because it must not alias. At most &T could get mutable access to the contents of some inner RefCell/Mutex/etc. -- not relevant here.


I'm sorry, I was going at the wrong point there, my bad. Basically self is now of type &T, in other words you can rewrite it as

fn foo(self: &mut Deserializer<'de>)

and this is implied as what you meant because self is &mut Deserializer<'de>. So changing self to &self or &mut self would end up with

fn foo(self: &mut &mut Deserializer<'de>)

Ignore the part about cloneing.