Weird method inference

Just saw this in the twir channel. Can anyone explain why this happens?

4 Likes

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 know x is i64, we prefer its inherent impls.


  1. We could, but I bet we'd hit a lot more ambiguities. ↩︎

6 Likes

Oookayyy… To my Cursed Rust Iceberg Tiers document this goes.

6 Likes

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.

10 Likes

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).

5 Likes