I started with Rust recently and I working on small game, unfortunately, I'm having issues on implementing a simple mechanic due an error of multiple mutable borrows, for instance, the following code has an issue with a second mutable borrow
struct Margin {
x: f32,
y: f32,
h: f32,
w: f32,
}
struct Level {
margins: Vec<Margin>,
}
impl Level {
fn new() -> Self {
Level{
margins: vec![]
}
}
fn update(&mut self) {
// Add a new margin on each tick
self.margins.push(Margin {
x:0., y:0., w:100., h:0.5,
});
// Iterate over margins moving each one down a little
for (i, m) in self.margins.iter_mut().enumerate() {
m.y += 1.;
// Remove margins outside of the screen
if m.y > 640. {
self.margins.remove(i);
}
}
}
}
fn main() {
let mut l = Level::new();
l.update();
}
Error
Compiling playground v0.0.1 (/playground)
error[E0499]: cannot borrow `self.margins` as mutable more than once at a time
--> src/main.rs:31:17
|
26 | for (i, m) in self.margins.iter_mut().enumerate() {
| -----------------------------------
| |
| first mutable borrow occurs here
| first borrow later used here
...
31 | self.margins.remove(i);
| ^^^^^^^^^^^^ second mutable borrow occurs here
Found the useful method retain on the Vec
and the code is fixed as follows:
struct Margin {
x: f32,
y: f32,
h: f32,
w: f32,
}
struct Level {
margins: Vec<Margin>,
}
impl Level {
fn new() -> Self {
Level{
margins: vec![]
}
}
fn update(&mut self) {
// Add a new margin on each tick
self.margins.push(Margin {
x:0., y:0., h:100., w:0.5,
});
// Iterate over margins moving each one down a little
for m in self.margins.iter_mut() {
m.y += 1.;
}
// Retains only the elements where y is lower than 640.
self.margins.retain(|v| v.y < 640.);
}
}
fn main() {
let mut l = Level::new();
l.update();
}
Answered based on a previous answer here Remove an element while iterationg over it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.