Skip to content

spurious error "cannot borrow *x as mutable more than once at a time" #63185

Open
@benw

Description

@benw
pub enum Foo<'a> {
    A(&'a mut u8),
    B(&'a mut Option<u8>),
}

pub fn foo(x: &mut Option<u8>) -> Foo {
    match *x {
        Some(ref mut y) if *y == 0 => Foo::A(y),
        ref mut z => Foo::B(z),
    }
}

(Playground)

warning[E0499]: cannot borrow `*x` as mutable more than once at a time
  --> src/lib.rs:10:9
   |
7  | pub fn foo(x: &mut Option<u8>) -> Foo {
   |               - let's call the lifetime of this reference `'1`
8  |     match *x {
9  |         Some(ref mut y) if *y == 0 => Foo::A(y),
   |              ---------                --------- returning this value requires that `x.0` is borrowed for `'1`
   |              |
   |              first mutable borrow occurs here
10 |         ref mut z => Foo::B(z),
   |         ^^^^^^^^^ second mutable borrow occurs here
   |
   = warning: this error has been downgraded to a warning for backwards compatibility with previous releases
   = warning: this represents potential undefined behavior in your code and this warning will become a hard error in the future

I fail to see any potential undefined behaviour in this code.

Removing the match arm guard allows this to compile.

Also weird that the error mentions x.0 when x is not a tuple.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-NLLArea: Non-lexical lifetimes (NLL)C-enhancementCategory: An issue proposing an enhancement or a PR with one.NLL-poloniusIssues related for using Polonius in the borrow checkerT-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