I am trying to learn rust on my own and I am struggling with the borrow checker. I have written a small program that has a struct State with a field board which is a vector. What I am trying to do wright a method for State which iterates over board and then returns a other State. If I try to give the method &self as it's first argument the compiler will say:
cannot move out of self.board
which is behind a shared reference
if I give it self instead: it will say:
borrow of moved value: 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 );
}