Skip to content

&mut self in loop #145313

@caojinyu

Description

@caojinyu

I tried this code:

fn alloc_raw(&mut self, bytes: usize) -> &mut [MaybeUninit<u8>] {
        if bytes == 0 {
            return &mut [];
        }

        loop {
            if let Some(a) = self.alloc_raw_without_grow(bytes) {
                return a;
            }
           // allocate new space
            self.grow(bytes);
        }
    }

I expected to see this happen: explanation

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> library/proc_macro/src/bridge/arena.rs:87:30
   |
81 |     fn alloc_raw(&mut self, bytes: usize) -> &mut [MaybeUninit<u8>] {
   |                  - let's call the lifetime of this reference `'1`
...
87 |             if let Some(a) = self.alloc_raw_without_grow(bytes) {
   |                              ^^^^ `*self` was mutably borrowed here in the previous iteration of the loop
88 |                 return a;
   |                        - returning this value requires that `*self` is borrowed for `'1`

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> library/proc_macro/src/bridge/arena.rs:91:13
   |
81 |     fn alloc_raw(&mut self, bytes: usize) -> &mut [MaybeUninit<u8>] {
   |                  - let's call the lifetime of this reference `'1`
...
87 |             if let Some(a) = self.alloc_raw_without_grow(bytes) {
   |                              ---- first mutable borrow occurs here
88 |                 return a;
   |                        - returning this value requires that `*self` is borrowed for `'1`
...
91 |             self.grow(bytes);
   |             ^^^^ second mutable borrow occurs here

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

Meta

rustc --version --verbose:

 rustc 1.89.0 (29483883e 2025-08-04)

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.fixed-by-poloniusCompiling with `-Zpolonius` fixes this issue.needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions