0

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).

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Parker Queen
  • 619
  • 2
  • 12
  • 27
  • @ÖmerErden I don't want to check the next element only. What I want to have is basically a for loop nested within a for loop and the inside for loop starts at the current index of the outside for loop. – Parker Queen Mar 22 '20 at 20:05
  • Hmm, even if you would solve the borrow issue this logic would not work, you need to update inner iteration on every outer iteration, your inner iterator simply iterates once then clones itself on every outer iteration.( With this it will always return true because it will compare same indexes, for non-empty ones) – Ömer Erden Mar 22 '20 at 20:14
  • 1
    I guess this is you are looking for: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3ab0c551842347cbe3d9ea252012d1b4 – Ömer Erden Mar 22 '20 at 20:39
  • @ÖmerErden yes, exactly what I wanted. – Parker Queen Mar 23 '20 at 17:08

0 Answers0