Borrow checker complains for closure inside loop if type not provided explicitly

Viewed 120

I have this code, for which borrow checker shows error:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=55d050b6f25410ce0e17ef9e844b048d

fn f1(v: &str) {
}

fn main() {
    let c = |v| f1(v);
    for _ in 0..1 {
        let s = String::new();
        c(&s);
    }
}
   |
10 |         c(&s);
   |         - ^^ borrowed value does not live long enough
   |         |
   |         borrow later used here
11 |     }
   |     - `s` dropped here while still borrowed

But if I add explicit type to closure, code compiles let c = |v: &str| f1(v);

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=54ca20dff5bdf1831ec705481e4936bb

Can someone explain why it works in second case and not in first, as I understand rust correctly infers same type in first example (as it works if I run closure outside of loop)?

0 Answers
Related