Just saw this in the twir channel. Can anyone explain why this happens?
From compiler-errors on Zulip:
For a given self type, we typically prefer inherent impls over traits when selecting methods.
However, since literals start out as numeric variables we can't assemble any inherent impls[1], so we just fall back to selecting trait impls first.
The trait impl here constrains the self type to
i64
since there's only one of them, and then once we knowx
isi64
, we prefer its inherent impls.
We could, but I bet we'd hit a lot more ambiguities. ↩︎
Oookayyy… To my Cursed Rust Iceberg Tiers document this goes.
I think “if there is only one possible type that satisfies these bounds, pick it” is one of the mistakes in Rust's design. Besides this particular case, it also means that adding trait implementations can be a breaking change, constraining the evolution of libraries (including std
) in surprising ways.
Integer fallback adds another wrinkle -- if there is more than one implementation, and i32
is one of the implementers, the type of the integer will remain ambiguous for both calls (so the inherent method is not considered; both calls "must" be trait calls), but the calls won't be considered ambiguous (because the fallback type does implement the trait).
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.