Why is this implicit deref allowed?
ā Rust š 2025-08-01 š¤ surdeus šļø 10Iā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:
- There is a coercion enabled by the
Dereftrait. - The type
&TimplementsDeref<Target = T>. - The above two implies that
&&i32can be coerced to&i32. - But, coercions can only occur at coercion sites and assignment expressions are not coercion sites.
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!
3 posts - 2 participants
š·ļø Rust_feed