Why is this implicit deref allowed?

I’m trying to figure why the following Rust snippet is allowed:

let mut a = &12;
let b = &&34;
a = b; // <- seems like &&i32 is coerced to &i32

This is a reduced version of Rust code I've seen in the wild. Here a has the inferred type &i32 and b has the inferred type &&i32. Yet, even though there not the same type, the assignment it allowed.

I can't find anything in the Rust reference explaining why this is legal. What I can find is:

In other words, I do understand why this slightly modified program is allowed:

let mut a = &12;
let b = &&34;
let c: &i32 = b; // <- allowed since annotated let is a coercion site

Am I missing something about coercions? Or is the some completely different mechanism at play here?

Thanks in advance for helping me out!

I'm quite sure they are, even though they are not explicitly mentioned in RFC 401, the Reference or the FLS. Found this previous topic on the matter:

Thanks for the answer @jofas. Ok, if that's the case then that explains it, but the behavior is not documented anywhere at all.

I suppose the Rust reference should be updated?

The reference should probably be updated, yes.

Basically, any situation where the the compiler can figure out what the target type is, is a coercion site.

1 Like

Alright, here's a PR for the reference:

Basically, any situation where the the compiler can figure out what the target type is, is a coercion site.

Assignment expressions as coercion sites feels a bit different to me compared to those documented in the reference.

In all those cases the coercion can be matched up with an explicit type annotation. For instance arguments are coercion sites and they can be matched to the parameter type annotation, let statements are only coercion sites when they have an annotation, etc.

For assignment expressions there may not be any annotation (like in my example) and yet a coercion can occur.

Here's another coercion with no annotations.

Thanks, good point. Argument coercion sites are not guaranteed to be matchable to a type annotation since closures don't require annotations.

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.