如何处理 rust borrow checker
How to deal with rust borrow checker
我正在尝试自己学习 Rust,但我正在与借用检查器作斗争。我写了一个小程序,它有一个结构状态和一个场板,它是一个矢量。我正在尝试做的是一种针对 State 的方法,该方法遍历 board 然后 returns 另一个 State。如果我尝试将方法 &self 作为第一个参数,编译器会说:
无法移出共享引用后面的 self.board
如果我给它自己:它会说:
借用移动的值:tmp
#[derive(Clone)]
#[derive(Debug)]
enum Color {
Empty,
Black,
White
}
#[derive(Debug)]
struct State{
board: Vec<Color>,
player: Color
}
impl State {
fn updat(&self, squares_to_be_changed: &Vec<Color>, new_player: &Color)->State{
let new_board = self.board.into_iter().zip(squares_to_be_changed.into_iter())
.map(|(old,updated)| match updated {
Color::Empty => old.clone(),
_ => updated.clone()
}).collect();
State {board: new_board, player: new_player.clone() }
}
}
fn main() {
let tmp = State {board: vec![Color::Empty;64], player: Color::Black};
let a = tmp.updat(&vec![Color::Black;64], &Color::Black);
print!("{:?}", tmp);
print!("{:?}",a );
}
这里的问题是使用 into_iter
字面上将 self
转换为 一个迭代器,在此过程中破坏了 self
。您可能想要的只是一个常规迭代器,或者:
self.board.iter().zip(...)
不消耗的地方self
。
我正在尝试自己学习 Rust,但我正在与借用检查器作斗争。我写了一个小程序,它有一个结构状态和一个场板,它是一个矢量。我正在尝试做的是一种针对 State 的方法,该方法遍历 board 然后 returns 另一个 State。如果我尝试将方法 &self 作为第一个参数,编译器会说:
无法移出共享引用后面的 self.board
如果我给它自己:它会说:
借用移动的值:tmp
#[derive(Clone)]
#[derive(Debug)]
enum Color {
Empty,
Black,
White
}
#[derive(Debug)]
struct State{
board: Vec<Color>,
player: Color
}
impl State {
fn updat(&self, squares_to_be_changed: &Vec<Color>, new_player: &Color)->State{
let new_board = self.board.into_iter().zip(squares_to_be_changed.into_iter())
.map(|(old,updated)| match updated {
Color::Empty => old.clone(),
_ => updated.clone()
}).collect();
State {board: new_board, player: new_player.clone() }
}
}
fn main() {
let tmp = State {board: vec![Color::Empty;64], player: Color::Black};
let a = tmp.updat(&vec![Color::Black;64], &Color::Black);
print!("{:?}", tmp);
print!("{:?}",a );
}
这里的问题是使用 into_iter
字面上将 self
转换为 一个迭代器,在此过程中破坏了 self
。您可能想要的只是一个常规迭代器,或者:
self.board.iter().zip(...)
不消耗的地方self
。