Skip to content

Detect need for partial self borrows in methods and suggest alternatives #147108

@estebank

Description

@estebank

When encountering methods where getters on self are used which cause borrow errors like the following:

error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
  --> src/lib.rs:20:17
   |
19 |         let a = self.get_a();
   |                 ---- immutable borrow occurs here
20 |         let b = self.get_mut_b();
   |                 ^^^^^^^^^^^^^^^^ mutable borrow occurs here
21 |         println!("{a:?} {b:?}");
   |                    - immutable borrow later used here

error[E0502]: cannot borrow `self.b` as mutable because it is also borrowed as immutable
  --> src/lib.rs:29:9
   |
29 |         self.b.bar(self.get_a());
   |         ^^^^^^^---^----^^^^^^^^^
   |         |      |   |
   |         |      |   immutable borrow occurs here
   |         |      immutable borrow later used by call
   |         mutable borrow occurs here

error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
  --> src/lib.rs:35:9
   |
35 |         self.bar(self.get_a());
   |         ^^^^^---^----^^^^^^^^^
   |         |    |   |
   |         |    |   immutable borrow occurs here
   |         |    immutable borrow later used by call
   |         mutable borrow occurs here

error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
  --> src/lib.rs:37:9
   |
37 |         self.bar(&self.a);
   |         ^^^^^---^-------^
   |         |    |   |
   |         |    |   immutable borrow occurs here
   |         |    immutable borrow later used by call
   |         mutable borrow occurs here

we should explain that get_a and get_mut_b borrow the entirety of Self making accessing any other method or field simultaneously will never work. If we ever get partial self borrows, then we should suggest it here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions