Skip to content

Getter functions and indexing don't seem to follow the same lifetime rules #58419

Open
@ejpbruel2

Description

@ejpbruel2

This is my first issue for the Rust project. Apologies up front if it is somehow unclear. I'd be happy to provide any additional information you need.

DESCRIPTION

The issue I'm running into is this. Consider the following code:
collection.get_mut(collection.get(0).unwrap().index).unwrap().index = 1;

The inner call to get causes an immutable borrow on collection. We then obtain a index from the return value, and use that for the outer call to get_mut. This causes a mutable borrow on collection.

The above code compiles just fine. My assumption is that because index implements Copy, NLL allow the immutable borrow on collection to be dropped as soon as we have a copy of index, so we can borrow it mutably again after that.

So far, so good. However, now consider the following code:
collection[collection[0].index].index = 1;

EXPECTED BEHAVIOR

This should be equivalent to the earlier code. In fact, I've implemented the Index trait to forward to get(index).unwrap().

ACTUAL BEHAVIOR

This time, however, the compiler complains:
error[E0502]: cannot borrow collection as immutable because it is also borrowed as mutable

For more context, here is a playground link that illustrates the problem:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=21d19fde2c8c58d4859bfdefa3b7720a

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-NLLArea: Non-lexical lifetimes (NLL)NLL-completeWorking towards the "valid code works" goalP-mediumMedium priorityT-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