问题
I'm implementing a double buffer in Rust, so when I get the current buffer, it does self.buffers[self.index]
.
For the sake of brevity, I made that into a function so I could call it like this:
pub struct Screen<'a> {
pub canvas: Canvas<'a>,
pub buffers: [Vec<u32>; 2],
pub index: usize,
}
impl<'a> Screen<'a> {
#[inline(always)]
pub fn get_buf<'b>(&'a self) -> &[u32] {
self.buffers[self.index].as_slice()
}
#[inline(always)]
pub fn get_mut_buf<'b>(&mut self) -> &mut [u32] {
self.buffers[self.index].as_mut_slice()
}
pub fn clear(&mut self, color: u32) {
for pixel in self.get_mut_buf().iter_mut() {
*pixel = color;
}
}
pub fn swap_buffers(&mut self) {
self.canvas.data.copy_from_slice(&self.buffers[self.index]);
self.index += 1;
if self.index >= self.buffers.len() {
self.index = 0;
}
}
}
The problem is this is invalid:
pub fn swap_buffers(&mut self) {
self.canvas.data.copy_from_slice(self.get_buf());
self.index += 1;
if self.index >= self.buffers.len() {
self.index = 0;
}
}
While this isn't:
pub fn swap_buffers(&mut self) {
self.canvas.data.copy_from_slice(&self.buffers[self.index]);
self.index += 1;
if self.index >= self.buffers.len() {
self.index = 0;
}
}
Is there a better way to do this?
I even tried encapsulating the real buffer inside a struct (in this case, Canvas) since I saw somewhere that could help because borrowing fields instead of the whole struct solves problems like these.
回答1:
In Rust you can't take a mutable reference and an immutable reference of the same thing at the same time. This is described nicely in the book here.
Basically in the second case the compiler is able to see that .canvas
and .buffers
are different things.
In the first case get_buf
returns a &[u32]
reference that has the same lifetime as &self
meaning that when self.get_buf()
is called it takes an immutable reference to the the entire Screen
struct. The compiler won't let you take a mutable reference to .canvas
because it is part of self
and you are already using an immutable reference to self
.
来源:https://stackoverflow.com/questions/63946390/cannot-infer-correct-lifetime-when-borrowing-index-of-slice-and-field-of-a-struc