reference icon indicating copy to clipboard operation
reference copied to clipboard

Mismatch between 'Warning' in 'Method call expressions' section and compiler behaviour

Open gslancaster opened this issue 1 year ago • 2 comments

The warning text in the doc says:

'Warning: For trait objects, if there is an inherent method of the same name as a trait method, it will give a compiler error when trying to call the method in a method call expression.' https://doc.rust-lang.org/reference/expressions/method-call-expr.html

However, the following Playground code compiles and calls the trait object method: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=ee3edd82619f479bdc9980c03b2f201f

This suggests that the warning is incorrect, and should be deleted.

gslancaster avatar Jul 09 '24 09:07 gslancaster

I think there may be a misunderstanding of what the text is saying. It is referring to methods on the trait, and one on the trait object. For example:

trait Bar {
    fn method(&self);
}

struct Foo;

impl Bar for Foo {
    fn method(&self) {
        println!("Bar::method");
    }
}

impl dyn Bar {
    fn method(&self) {
        println!("dyn Bar");
    }
}

fn main() {
    let x: &dyn Bar = &Foo;
    x.method();
}

impl dyn adds methods to the trait object which is different from the trait itself.

ehuss avatar Jul 09 '24 13:07 ehuss

Ah, I see.

The issue with the text is that 'inherent method' of a 'trait object' is ambiguous. It could mean, in the context of the example:

  1. A method defined inside an impl Foo block, or
  2. A method defined inside an impl dyn Bar block

Given that (1) is a far more common usage in Rust than (2), I suspect most will read it that way.

Placing your example, @ehuss, in the text, would certainly aid understanding, and perhaps rewording the text somehow to further clarify.

gslancaster avatar Jul 10 '24 10:07 gslancaster