Idiomatic: Simplify example in method resolution slide - #3166
Idiomatic: Simplify example in method resolution slide#3166randomPoison wants to merge 2 commits into
Conversation
| `&mut self` has a higher priority than `&self`, the one used by the inherent | ||
| method. | ||
| Demonstrate: Change the call to `(&-1i32).count_ones()` and demonstrate that | ||
| the trait method is now called instead. |
There was a problem hiding this comment.
I'm not sure that this new example demonstrates the rule described above. Could you help me understand? The difference is the method receiver expression, value -1i32 vs. reference &-1i32. The list above that describes the rule does not talk about that axis?
There was a problem hiding this comment.
Ah yeah good point, the explanation here is wrong too (or at least not fully accurate). After staring at the reference for an hour (and then begging Codex to explain it again but slower), it looks like the reason the & changes resolution is because method resolution searches based on the receiver type, and adding the & changes the order in which it searches the receivers.
When resolving a method, rustc builds a list of candidate receiver types by repeatedly dereferencing and then adding & and &mut. It then searches for methods (both inherent and trait ones) that have the candidate receiver type. When we do (-1i32).count_ones() the candidate list is:
i32 -> &i32 -> &mut i32When we do (&-1i32).count_ones(), the candidate list is:
&i32 -> &&i32 -> &mut &i32 -> i32 -> &i32 -> &mut i32In the latter case, it looks for methods that take &i32 before it looks for methods that take i32, so it finds the trait method first. The explanation above is somewhat accurate in that in some cases it will search for &self methods before &mut self methods in some cases, but that's not always the case if a deref is involved.
All that being said, I don't think we should go into the details of method resolution here. I think the main thing to point out is "method resolution mostly Just Works, but it can be subtle and hard to reason about if trait methods overlap inherent methods, so try to avoid that." I'll update the speaker notes to make this more concise and accurate.
There was a problem hiding this comment.
Okay I've reworked the speaker notes to be more concise, and to more directly frame the discussion of method resolution as "method resolution can be confusing when inherent methods and trait methods overlap, so avoid overlap if possible", and fleshed out the suggested demonstration to illustrate that subtlety.
Head branch was pushed to by a user without write access
The example in the speaker notes can be a bit simpler, i.e. we can do
&instead of&mutand get the same effect. I also cut the comment down to reduce verbosity.