rust-lang / rust-lang/rust

doesn't point out the arbitrary self type is wrong

Open
#138,440 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Consider this code:

use std::sync::Arc;

struct Foo;
impl Foo {
    fn bar(&self) {
        self.hello_world_next();
    }
    fn hello_world(&self) {}
    fn hello_world_next(self: &Arc<Self>) {}
}
fn main() {}

it will error as bar takes &self but hello_world_next takes &Arc<Self>. We give a suboptimal error here though:

error[E0599]: no method named `hello_world_next` found for reference `&Foo` in the current scope
 --> src/main.rs:6:14
  |
6 |         self.hello_world_next();
  |              ^^^^^^^^^^^^^^^^
  |
help: there is a method `hello_world` with a similar name
  |
6 -         self.hello_world_next();
6 +         self.hello_world();
  |

For more information about this error, try `rustc --explain E0599`.

We should instead suggest that hello_world_next exists as a function, but takes &Arc<Self> as type so can't be used.

If one puts &mut self instead of &Arc<Self>, it gives a nicer error:

error[E0596]: cannot borrow `*self` as mutable, as it is behind a `&` reference
 --> a.rs:6:9
  |
6 |         self.hello_world_next();
  |         ^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
  |
help: consider changing this to be a mutable reference
  |
5 |     fn bar(&mut self) {
  |             +++

error: aborting due to 1 previous error; 1 warning emitted

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by compiling the Rust snippet and compare the diagnostics for arbitrary self types with the existing [?2004l[?2004h&mut self case. Trace the method lookup and diagnostic path for the failed hello_world_next call; done means the diagnostic identifies the existing method and explains that its &Arc receiver cannot be used from &self.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.