【发布时间】:2020-11-08 01:30:14
【问题描述】:
我正在尝试自己学习 Rust,但我正在努力使用借用检查器。我写了一个小程序,它有一个结构状态和一个字段板,它是一个向量。我正在尝试为 State 编写一个方法,该方法在船上进行迭代,然后返回另一个 State。如果我尝试将方法 &self 作为它的第一个参数,编译器会说:
无法移出共享引用后面的self.board
如果我给它 self:它会说:
借用移动值: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 );
}
【问题讨论】:
标签: rust borrow-checker