Redundant type hinting makes seemingly invalid code compile

Doesn't compile


As far as I can tell, the second example shouldn’t compile either, as a move still occurs.
Am I missing something or is it a compiler bug?

Found here

This is silly indeed. I think what happens is that explicit type provokes a type coercion or a reborrow, which effectively works the same as:

    let _a = &mut *t;
    let _b = t;

In Rust &mut is not trivially copyable with Copy, but you can make temporary/limited copies of it by reborrowing.


It’s not so much that we “state that we are fine with a reference reborrow” as the answer on Twitter 𝕏 implies, and more so that the logic of introducing implicit reborrows in the Rust compiler runs before type inference[1], so it only introduces re-borrows for mutable references in places that are known accept a mutable reference before type inference was run, so that explicit type signatures, unfortunately, make a difference here in what is or isn’t accepted.

I personally hope that eventually the compiler could be made to accept both versions of the code equally.

  1. for full disclosure, I have never checked the actual code on this, but this is my take from observed behavior of what programs are and aren’t accepted ↩︎


Thank you both :slight_smile:

The arguably even more common occurrence of this distinction is that if you pass a mutable reference to a function, if the signature is something like fn foo(r: &mut Bar), then foo(x) reborrows from x, but if it’s fn foo2<T>(r: T) then foo2(x) moves x. The typical workaround then would be explicit reborrow, i.e. calling it as foo2(&mut *x); but technically, even specifying the type signature works, so foo2::<&mut _>(x)[1] makes it a reborrow again, too.

  1. you can still leave the target type inferred, it’s just important that pre-type-inference it’s clear that it’s expecting some mutable reference type. ↩︎


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.