Skip to content

Spurious reborrowing errors when returning lifetimes referencing mutable borrows from inside loops #113322

Open
@dead-claudia

Description

@dead-claudia

I tried this code:

struct Foo {
    value: u32,
}

impl Foo {
    pub fn next<'a>(&'a mut self) -> &'a u32 {
        loop {
            self.value = 123;

            let value = &self.value;

            static COND: bool = true;
            if COND {
                return value;
            }
        }
    }
}

I expected to see this happen: It to compile successfully, like it does without the loop:

struct Foo {
    value: u32,
}

impl Foo {
    pub fn next<'a>(&'a mut self) -> &'a u32 {
        self.value = 123;

        let value = &self.value;

        static COND: bool = true;
        if COND {
            return value;
        }

        panic!()
    }
}

Instead, this happened:

error[E0506]: cannot assign to `self.value` because it is borrowed
  --> <source>:8:13
   |
6  |     pub fn next<'a>(&'a mut self) -> &'a u32 {
   |                 -- lifetime `'a` defined here
7  |         loop {
8  |             self.value = 123;
   |             ^^^^^^^^^^^^^^^^ `self.value` is assigned to here but it was already borrowed
9  |
10 |             let value = &self.value;
   |                         ----------- `self.value` is borrowed here
...
14 |                 return value;
   |                        ----- returning this value requires that `self.value` is borrowed for `'a`

error: aborting due to previous error

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

Meta

rustc --version --verbose:

rustc 1.70.0 (90c541806 2023-05-31)
binary: rustc
commit-hash: 90c541806f23a127002de5b4038be731ba1458ca
commit-date: 2023-05-31
host: x86_64-pc-windows-msvc
release: 1.70.0
LLVM version: 16.0.2

Also repros on nightly: https://godbolt.org/z/hEdjnz5oE

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerC-bugCategory: This is a bug.S-has-mcveStatus: A Minimal Complete and Verifiable Example has been found for this issueT-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

    Development

    No branches or pull requests

    Issue actions