rust-lang/rust

Method resolution for trait object types does not prefer inherent methods

withoutboats opened this issue · 8 comments

Normally, inherent methods are given precedence over all trait methods, so that there is no ambiguity.

However, this behavior does not appear to be implemented for trait object types:

trait Foo {
    fn f(&self) { }
}

impl Foo {
    fn f(&self) { }
}

impl Foo for i32 { }

struct Bar;

impl Bar {
    fn f(&self) { }
}

impl Foo for Bar { }

fn main() {
    let x: &Foo = &42i32;
    x.f();
    let bar: &Bar = &Bar;
    bar.f();
}

https://play.rust-lang.org/?gist=7d4534a5d973249c66244b9affa03199&version=stable&mode=debug

What's worse, UFCS does not allow for specifying that you want the inherent method, because Foo::f(x) in this code will remain ambiguous. In general, UFCS isn't designed to support disambiguating to inherent methods because inherent methods are supposed to always take precedence.

Tagging and nominating to discuss whether this behavior is a bug or intended.

sgrif commented

Worth noting in any discussion around this that since inherent methods can only be defined in the same crate as the type, this would only affect any crate which intentionally tried to provide an inherent method for a trait object with the same name as a method on the trait itself.

Niko explained to me that this issue is actually inverted from what I thought: all trait methods are considered inherent methods of the trait object type. I've removed the I-nominated tag.

However, in my use case there's this interesting problem, which can be demonstrated roughly like this:

trait Foo {
    fn dynamic(&self) -> &dyn Foo where Self: SIzed { self as &dyn Foo }
}

impl dyn Foo {
    fn dynamic(&self) -> &dyn Foo { self }
}

The conversion requires where Self: Sized on the method.

There's no way to provide a method with a single name for all Sized impls and for the trait object type today.

Havvy commented

It'd be backwards compatible to remove the whole trait methods are psuedo-inherent methods on trait objects thing. And it seems to be causing more confusion than it seems to save. It's also one extra complexity in the language that's already complex enough.

A more conservative option is to only have inherent methods for the methods that are object safe. So in the case of the where Self: Sized fns, the trait object wouldn't have them as inherent methods.

@Diggsey

actually, it is possible if you use an additional trait

But the user has to explicitly import that trait, which is worse for discoverability and for typing in less advanced IDEs.

Rua commented

I just ran into this issue, pretty much in the situation described by @withoutboats. In my case, the return type contains Self but it's the same idea.