Skip to content

Erroneous borrowck error with early returns #58910

Open
@nox

Description

@nox

Playground

use syn::spanned::Spanned;
use syn::{Data, DeriveInput, Error, Field, Fields};

// Uncommenting the two lines below trigger a borrowck error.

pub fn struct_fields_mut(
    input: &mut DeriveInput,
) -> Result<impl Iterator<Item = &mut Field>, Error> {
    if let Data::Struct(ref mut data_struct) = input.data {
        //if let Fields::Named(_) = data_struct.fields {
            return Ok(data_struct.fields.iter_mut());
        //}
    }
    Err(Error::new(
        input.span(),
        "only structs can be automatically neutralized",
    ))
}
error[E0502]: cannot borrow `input` as immutable because it is also borrowed as mutable
  --> src/lib.rs:15:9
   |
7  |     input: &mut DeriveInput,
   |            - let's call the lifetime of this reference `'1`
8  | ) -> Result<impl Iterator<Item = &mut Field>, Error> {
9  |     if let Data::Struct(ref mut data_struct) = input.data {
   |                         ------------------- mutable borrow occurs here
10 |         if let Fields::Named(_) = data_struct.fields {
11 |             return Ok(data_struct.fields.iter_mut());
   |                    --------------------------------- returning this value requires that `input.data.0` is borrowed for `'1`
...
15 |         input.span(),
   |         ^^^^^ immutable borrow occurs here

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-NLLArea: Non-lexical lifetimes (NLL)A-borrow-checkerArea: The borrow checkerC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.fixed-by-poloniusCompiling with `-Zpolonius` fixes this issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions