Skip to content

Incorrect suggestion when trying to write to an immutable field in an async function #93093

Closed
@jyn514

Description

@jyn514

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=df6e36b97b73bd3e3ea0fdfe9325b1c9

struct S { foo: usize }
impl S {
    async fn bar(&self) {
        self.foo += 1;
    }
}

The current output is:

error[E0594]: cannot assign to `self.foo`, which is behind a `&` reference
 --> src/lib.rs:4:9
  |
3 |     async fn bar(&self) {
  |                  ----- help: consider changing this to be a mutable reference: `&mut S`
4 |         self.foo += 1;
  |         ^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be written

Ideally the output should look like:

error[E0594]: cannot assign to `self.foo`, which is behind a `&` reference
 --> src/lib.rs:4:9
  |
3 |     async fn bar(&self) {
  |                  ----- help: consider changing this to be a mutable reference: `&mut self`
4 |         self.foo += 1;
  |         ^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be written

&mut S is not a valid argument; it needs to be either &mut self or some_name: &mut S. For some reason this problem only happens when the function is async.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-async-awaitArea: Async & AwaitA-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`AsyncAwait-PolishAsync-await issues that are part of the "polish" areaAsyncAwait-TriagedAsync-await issues that have been triaged during a working group meeting.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions