Unintuitive behaviour with passing a reference to trait object to function

demo3 works because you are creating a H hasher, where H : Hasher /* + Sized */, there is no dyn Hasher there.

demo2 works because for all <T : ?Sized> the type H = &'_ mut T is itself Hasher when T : Hasher, thanks to a generic impl that delegates to the referred Thing: mod.rs.html -- source

In your case, T = dyn Hasher so H = &mut dyn Hasher, which becomes Sized thanks to indirection (a reference is always Sized, in the case of a reference to a dyn Trait object it has the size of two pointers, as explained in this other post of mine: What's the difference between T: Trait and dyn Trait? - #3 by Yandros). Since the .hash() function takes a &mut (H), that leaves us with a &mut (&mut dyn Hasher)

3 Likes