[英]How to deal with rust borrow checker
I am trying to learn rust on my own and I am struggling with the borrow checker.我正在尝试自己学习 Rust,但我正在努力使用借用检查器。 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.我正在尝试为 State 做一个方法,该方法在船上迭代然后返回另一个状态。 If I try to give the method &self as it's first argument the compiler will say:如果我尝试将方法 &self 作为第一个参数,编译器会说:
cannot move out of self.board
which is behind a shared reference无法移出位于共享引用后面的self.board
if I give it self instead: it will say:如果我给它自己:它会说:
borrow of moved value: tmp
借用移动值: 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 );
}
Here the problem is the use of into_iter
which literally converts self
into an iterator, destroying self
in the process.这里的问题是使用into_iter
,它实际上将self
转换为迭代器,在此过程中销毁self
。 What you probably want is just a regular iterator, or:您可能想要的只是一个常规迭代器,或者:
self.board.iter().zip(...)
Where that doesn't consume self
.哪里不消耗self
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.