Skip to content

When a function name within a method is not found, suggest calling the method of the same name #103474

Closed
@jruderman

Description

@jruderman
Contributor

Given the following code (playground):

struct S { }
impl S {
    fn first(&self) { }
    fn second(&self) { first() }
}

The current output is:

error[[E0425]](https://doc.rust-lang.org/nightly/error-index.html#E0425): cannot find function `first` in this scope
 --> src/lib.rs:4:24
  |
4 |     fn second(&self) { first() }
  |                        ^^^^^ not found in this scope

Ideally the output should mention the fact that a method with this name was found on the same struct. And perhaps suggest calling the method on self, especially if the self-param types are compatible (e.g. both take an immutable &self reference).

note: A method named `first` was found on `S`.
help:
  |
4 |     fn second(&self) { self.first() }
  |                        +++++   specify which instance of `S` to call `first` on

Motivation

This may be a common error for programmers coming from C++, because C++ does not require specifying the instance for method-to-method calls.

C++ example

#include <iostream>
using namespace std;

class C {
    public:
        int jj() { return 1; }
        int kk() { return 5 + jj(); }
};


int main() {
    C *c = new C();
    printf("%d", c->kk());
}

Activity

added
A-diagnosticsArea: Messages for errors, warnings, and lints
T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.
on Oct 24, 2022
kpreid

kpreid commented on Oct 24, 2022

@kpreid
Contributor

A similar issue: #102518, about suggesting methods when trying free functions in general, not specifically within an impl. An impl gives even more reason to prioritize the suggestion.

This may be a common error for programmers coming from C++,

Java and C# also do this.

chenyukang

chenyukang commented on Oct 25, 2022

@chenyukang
Member

@rustbot claim

added 3 commits that reference this issue on Nov 11, 2022

Rollup merge of rust-lang#103531 - chenyukang:yukang/fix-103474, r=es…

be70abe

Rollup merge of rust-lang#103531 - chenyukang:yukang/fix-103474, r=es…

ba1ead5

Rollup merge of rust-lang#103531 - chenyukang:yukang/fix-103474, r=es…

f00897e
added a commit that references this issue on Jan 6, 2023

Rollup merge of rust-lang#103531 - chenyukang:yukang/fix-103474, r=es…

6037a3a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

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

    Participants

    @chenyukang@jruderman@kpreid

    Issue actions

      When a function name within a method is not found, suggest calling the method of the same name · Issue #103474 · rust-lang/rust