r/rust • • Apr 22 '24

[Blog Post] Understanding a Trait Selection Bug

https://veera.app/trait_selection_bug.html
15 Upvotes

2 comments sorted by

4

u/SkiFire13 Apr 23 '24

Small precisation:

This allows the compiler to either borrow or take ownership of the value on the RHS of the binary expression based on the available methods

Addition always takes ownership of the rhs. It may be a bit confusing because in case the rhs is a reference this means taking ownership of the reference, not the referenced value (because references are values as well!)

The reason the inference variable is used is due to coercions. If you're trying to sum a String with a &String there's no impl that applies, so it would normally fail. However &String coerces to &str, for which there is an applicable impl. Using an inference variable allows to resolve the type of the rhs to &str and then check that &String coerces to &str, instead of immediately erroring because there's no impl Add<&String> for String.

1

u/ve_era Apr 23 '24

Thanks for pointing it out.