rust icon indicating copy to clipboard operation
rust copied to clipboard

Questionable suggestion to use `dyn` in UFCS syntax

Open mcy opened this issue 3 years ago • 0 comments

Given the following code:

struct MyType(u32);

impl std::fmt::Display for MyType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        <std::fmt::Octal>::fmt(&self.0, f)
    }
}

The current output is:

error[E0782]: trait objects must include the `dyn` keyword
 --> <source>:5:10
  |
5 |         <std::fmt::Octal>::fmt(&self.0, f)
  |          ^^^^^^^^^^^^^^^
  |
help: add `dyn` keyword before this trait
  |
5 |         <dyn std::fmt::Octal>::fmt(&self.0, f)
  |          +++

error[E0782]: trait objects without an explicit `dyn` are deprecated
 --> <source>:5:10
  |
5 |         <std::fmt::Octal>::fmt(&self.0, f)
  |          ^^^^^^^^^^^^^^^ help: use `dyn`: `dyn std::fmt::Octal`

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0782`.
Compiler returned: 1

This is correct, but a red herring. What the author is trying to do is <Trait>::foo() instead of Trait::foo(); because Rust expects a type in <$ty>::foo(), it falls back to "it's a trait object!". The correct suggested remediation should be one of:

  • std::fmt::Octal::fmt(...)
  • <_ as std::fmt::Octal>::fmt(...)

Note that these suggestions only make sense for trait functions that take self; in any other case it should fall back to seeing <Trait>::foo() as Trait::foo() and emitting the relevant diagnostic.

mcy avatar May 12 '22 17:05 mcy