Skip to content

Have for pattern in iter not borrow the iterator #8372

Closed
@SimonSapin

Description

@SimonSapin

Test case:

let mut iter = range(1, 10);
for i in iter {
    printfln!(i);
    // error: cannot borrow `iter` as mutable more than once at a time
    printfln!(iter.next());
}

The above currently fails, but I think it should be valid and equivalent to:

let mut iter = range(1, 10);
loop { match iter.next() { None => break, Some(i) => {
    printfln!(i);
    printfln!(iter.next());
}}

In other words, the for loop should only borrow the iterator long enough to call next(), leaving the loop body free to use it.

I understand that this might not be possible when a more complex expression is used as the iterator. The for loop needs to evaluate the expression once and keep the result in an anonymous variable, thus borrowing. Maybe there could be a special case when the iterator expression is "simple" enough: a variable, struct field access, etc?

Metadata

Metadata

Assignees

No one assigned

    Labels

    P-lowLow priority

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions