Hello everyone,
As a learning exercise I implemented heapsort in rust. It was fun but I wanted to find a way of showing off with it, so I pillaged termions rainbow example to display the heapsort on RGB colors.
My data is contained in a struct :
pub struct Rainbow {
rgb: Vec<Vec<u8>>,
}
where rgb
is a vector of three Vec<u8>
vectors, one for red, one for green, one for blue. Each vector has a 255 length.
Here is what happens when I successively:
- Generate three vectors of the shape [0, 1, 2, .. 254] for each color
- Scramble the red
- Scramble the green
- Scramble the blue
- Heapify the red (pre-sort it in a binary heap)
- Heapify the green
- Heapify the blue
- Heapsort the red
- Heapsort the green
- Heapsort the blue
My problem
I am very happy, as you can imagine, but my limitation is that all the above steps are performed like this:
- Call a scramble/sorting function on a mutable reference of a vector.
heapsort(&mut rainbow.rgb[i]);
- Call the display function on an immutable reference of the whole struct.
show(&mut stdout, &rainbow);
It works perfectly well until I try do display every single step of the sorting algorithms. My goal is to mutate data AND display it on the fly. So I try to call the show function INSIDE the scramble/sorting functions by doing this:
pub fn heapify<W: Write>(mut stdout: &mut W, vector: &mut Vec<u8>, rainbow: &Rainbow) {
// a loop that performs operantions on vector {
show(&mut stdout, &rainbow);
//}
}
// here is the signature of the show() function, by the way:
pub fn show<W: Write>(stdout: &mut W, rainbow: &Rainbow) {}
I get that beloved message:
error[E0502]: cannot borrow `rainbow` as immutable because it is also borrowed as mutable
--> src/main.rs:26:51
|
26 | heapify(&mut stdout, &mut rainbow.rgb[i], &rainbow);
| ------- ----------- ^^^^^^^^ immutable borrow occurs here
| | |
| | mutable borrow occurs here
| mutable borrow later used by call
I understand fairly well why I can't do that. But is there anything I can do?