Take a look at this function:
fn pair_repetition(input: &String) -> bool {
let mut pairs = input.chars().skip(1).zip(input.chars());
pairs.any(|(a, b)| pairs.clone().skip(1).any(|(c, d)| a == c && b == d))
}
This function is checking if a pair of characters repeats in a string (in a non-overlapping fashion).
Now, in the last expression, I'm using any
on pairs
and passing a closure which attempts to clone the original iterator pairs
. But the compiler of course doesn't allow this because the outer any
tries to mutably borrow pairs
which has been immutably borrowed for use inside the closure. Here is the error:
error[E0502]: cannot borrow `pairs` as mutable because it is also borrowed as immutable
--> src/lib.rs:3:5
|
3 | pairs.any(|(a, b)| pairs.clone().skip(1).any(|(c, d)| a == c && b == d))
| ^^^^^^---^--------^-----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| | | | |
| | | | first borrow occurs due to use of `pairs` in closure
| | | immutable borrow occurs here
| | immutable borrow later used by call
| mutable borrow occurs here
What would be a way to achieve what I'm trying to do in a functional style? (I'm deliberately avoiding loops to get comfortable with the closure-style of things).