Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I repeatedly borrow the variable outside the closure in different closures in Rust?

This is the core codes, which return the type of Vec<(&'a str, i32)>
When I run this code,

let mut i = 0;
contents.lines().filter(|x| {
    i += 1;
    x.to_lowercase().contains(&query.to_lowercase())
}).map(|x|
    (x, i)
).collect()

it alerts that:

contents.lines().filter(|x| {
   |                             --- mutable borrow occurs here
56 |         i += 1;
   |         - first borrow occurs due to use of `i` in closure
57 |         x.to_lowercase().contains(&query.to_lowercase())
58 |     }).map(|x|
   |        --- ^^^ immutable borrow occurs here
   |        |
   |        mutable borrow later used by call
59 |         (x, i)
   |             - second borrow occurs due to use of `i` in closure

So how can I correct this code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The best way to fix this code is to realize that what you’re doing is essentially enumerate() with index starting from 1 instead of zero, so either:

contents.lines().enumerate().filter(|(_, x)| {
    x.to_lowercase().contains(&query.to_lowercase())
}).map(|(i, x)|
    (x, i + 1)
).collect()

Or:

contents.lines().zip(1..).filter(|(x, _)| {
    x.to_lowercase().contains(&query.to_lowercase())
}).collect()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading