Mutable borrow scoping

What is wrong with the following usage:

let mut slices = Vec::new();, &mut slices);, &mut slices);, &mut slices);

for slice in slices {

The compiler says - first mutable borrow occurs in the first foo() invocation and second one in the second foo() invocation. Same error for the goo() invocation. But I don't understand it. The calls are synchronous so what am I missing here.

Might be a problem of lifetime being overconstrained.

But do provide full code before asking why your code doesn't work.

How long a function argument is considered borrowed for depends on the signature of the function, so we'd have to see the declarations to be 100% certain. However, simple, idiomatic code doesn't exhibit this kind of error. A typical antipattern you might be writing is an invariant lifetime in the function signature declared to be equal to a generic parameter of the implementing type: Playground

struct Foo<'a>(&'a mut String);

impl<'a> Foo<'a> { 
    async fn foo(&mut self, _: &'a mut String) {}

fn main() {
    let mut s = String::new();
    let mut tmp = String::new();
    let mut f = Foo(&mut tmp); s); s);

The solution to this problem is usually to remove the explicit lifetime from the signature.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.