1
votes

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 );
}
1

1 Answers

2
votes

Here the problem is the use of into_iter which literally converts self into an iterator, destroying self in the process. What you probably want is just a regular iterator, or:

self.board.iter().zip(...)

Where that doesn't consume self.