Skip to content

Borrowing &mut multiple times in fn argument list fails, although the borrows do not overlap. #7448

@michaelwoerister

Description

@michaelwoerister

I recently had a case where a function needed an argument prepared by another function. Both functions take the same &mut (they both update a cache reachable through that reference). However, I had to pull the argument preparation call out of the argument list to avoid a cannot borrow ... as mutable more than once at a time error. Here is a minimal test case:

fn g(x: &mut int) -> int {
    *x
}

fn f(x: &mut int, y: int) {
    *x += y;
}

fn main() {
    let mut a = 1;

    // This works:
    let tmp = g(&mut a);
    f(&mut a, tmp);

    // This is essentially the same, but fails the borrow check
    f(&mut a, g(&mut a));
}

Maybe I'm overlooking something here, but I think the second call should work too, as the ref borrowed by g() is returned before it is borrowed by f().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions