I encountered a problem with lifetimes:
fn solve_hanoi<'a>(
a: &'a mut Vec<u8>,
b: &'a mut Vec<u8>,
c: &'a mut Vec<u8>,
depth: u8,
deshuffle: fn(&'a Vec<u8>, &'a Vec<u8>, &'a Vec<u8>) -> (&'a Vec<u8>, &'a Vec<u8>, &'a Vec<u8>),
) {
if depth == 0 {
return;
} else {
solve_hanoi(a, c, b, depth - 1, |a_, c_, b_| (a_, b_, c_));
c.push(a.pop().unwrap()); // the actual move
{
let (a_, b_, c_) = deshuffle(a, b, c);
print_hanoi(a_, b_, c_);
}
solve_hanoi(b, a, c, depth - 1, |b_, a_, c_| (a_, b_, c_));
}
}
fn print_hanoi(_: &Vec<u8>, _: &Vec<u8>, _: &Vec<u8>) {}
The purpose of deshuffle is to make sure the printed towers are always in the same order, even when the order of values in the parameters changes. However, the compiler complains:
error[E0502]: cannot borrow `*b` as mutable because it is also borrowed as immutable
--> src/lib.rs:20:9
|
1 | fn solve_hanoi<'a>(
| -- lifetime `'a` defined here
...
16 | let (a_, b_, c_) = deshuffle(a, b, c);
| ------------------
| | |
| | immutable borrow occurs here
| argument requires that `*b` is borrowed for `'a`
...
20 | solve_hanoi(b, a, c, depth - 1, |b_, a_, c_| (a_, b_, c_));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
error[E0502]: cannot borrow `*a` as mutable because it is also borrowed as immutable
--> src/lib.rs:20:9
|
1 | fn solve_hanoi<'a>(
| -- lifetime `'a` defined here
...
16 | let (a_, b_, c_) = deshuffle(a, b, c);
| ------------------
| | |
| | immutable borrow occurs here
| argument requires that `*a` is borrowed for `'a`
...
20 | solve_hanoi(b, a, c, depth - 1, |b_, a_, c_| (a_, b_, c_));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
error[E0502]: cannot borrow `*c` as mutable because it is also borrowed as immutable
--> src/lib.rs:20:9
|
1 | fn solve_hanoi<'a>(
| -- lifetime `'a` defined here
...
16 | let (a_, b_, c_) = deshuffle(a, b, c);
| ------------------
| | |
| | immutable borrow occurs here
| argument requires that `*c` is borrowed for `'a`
...
20 | solve_hanoi(b, a, c, depth - 1, |b_, a_, c_| (a_, b_, c_));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
I tried various different combinations of lifetime annotations, but there was always some problem. How do I tell the compiler that the immutable references that are passed into the deshuffle function no longer exist when solve_hanoi is called for the second time?