Skip to content

for borrowing lasts after the end of the for loop #38614

Closed
@progval

Description

@progval

Hi,

The following code:

fn method(vector: &mut Vec<u64>) -> &u64 {
    {
        for item in vector.iter() {
            return item
        }
    }

    vector.last_mut().unwrap()
}

Raises an error about vector.iter()'s borrow conflicting with vector.last_mut():

error[E0502]: cannot borrow `*vector` as mutable because it is also borrowed as immutable
 --> <anon>:8:5
  |
3 |         for item in vector.iter() {
  |                     ------ immutable borrow occurs here
...
8 |     vector.last_mut().unwrap()
  |     ^^^^^^ mutable borrow occurs here
9 | }
  | - immutable borrow ends here

However, I would have expected the first borrow to end with the first closing bracket.

Playground URL: https://play.rust-lang.org/?gist=36c206ebc1f8c96b96978a628b5c09a9&version=stable&backtrace=0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions