Skip to content

confusing error when trying to call a not-in-scope method that shares a name with a field #127178

Open
@lolbinarycat

Description

@lolbinarycat

Code

struct Struct { x: u8 }

mod m {
    trait GetX {
        fn x(&self) -> u8;
    }
    
    impl GetX for super::Struct {
        fn x(&self) -> u8 {
            self.x
        }
    }
}

pub fn show_x(st: Struct) {
    println!("{}", st.x())
}

Current output

error[E0599]: no method named `x` found for struct `Struct` in the current scope
  --> src/lib.rs:16:23
   |
1  | struct Struct { x: u8 }
   | ------------- method `x` not found for this struct
...
16 |     println!("{}", st.x())
   |                       ^ field, not a method
   |
   = help: items from traits can only be used if the trait is implemented and in scope
help: remove the arguments
   |
16 -     println!("{}", st.x())
16 +     println!("{}", st.x)
   |
help: trait `GetX` which provides `x` is implemented but not in scope; perhaps you want to import it
   |
1  + use crate::m::GetX;
   |

Desired output

error[E0599]: no method named `x` found for struct `Struct` in the current scope
  --> src/lib.rs:16:23
   |
1  | struct Struct { x: u8 }
   | ------------- method `x` not found for this struct
...
16 |     println!("{}", st.x())
   |                       ^ field, method not in-scope
   |
   = help: items from traits can only be used if the trait is implemented and in scope
help: trait `GetX` which provides `x` is implemented but not in scope; perhaps you want to import it
   |
1  + use crate::m::GetX;
   |
help: remove the arguments
   |
16 -     println!("{}", st.x())
16 +     println!("{}", st.x)
   |

Rationale and extra context

No response

Other cases

there should also be a unit test to make sure the output makes since when the field is not available directly, but instead by `Deref` coercion.  it is extremely confusing to see "field, not a method" when a type's documentation lists it as a method, but not a field.

Rust Version

rustc 1.81.0-nightly (8337ba918 2024-06-12)
binary: rustc
commit-hash: 8337ba9189de188e2ed417018af2bf17a57d51ac
commit-date: 2024-06-12
host: x86_64-unknown-linux-gnu
release: 1.81.0-nightly
LLVM version: 18.1.7

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions