[英]Issues with a second borrow in rust
我最近從 Rust 開始,我正在研究小游戲,不幸的是,由於多個可變借用的錯誤,我在實現一個簡單的機制時遇到了問題,例如,以下代碼有第二個可變借用的問題
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();
}
錯誤
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
在Vec
上找到有用的方法retain ,代碼固定如下:
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();
}
根據之前的答案回答這里刪除一個元素,同時迭代它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.