【发布时间】:2017-05-30 13:35:13
【问题描述】:
我在尝试解决 the robot simulator Exercism exercise 时获得了很多乐趣,但我面临着一个价值转移问题,我似乎无法想出一个优雅的解决方案:
impl Robot {
pub fn new(x: isize, y: isize, d: Direction) -> Self {
Robot { position: Coordinate { x: x, y: y }, direction: d }
}
pub fn turn_right(mut self) -> Self {
match self.direction {
// ...
};
self
}
pub fn turn_left(mut self) -> Self {
match self.direction {
// ...
};
self
}
pub fn advance(mut self) -> Self {
match self.direction {
// ...
};
self
}
pub fn instructions(self, instructions: &str) -> Self {
for instruction in instructions.chars() {
match instruction {
'A' => { self.advance(); },
'R' => { self.turn_right(); },
'L' => { self.turn_left(); },
_ => {
println!("{} is not a valid instruction", instruction);
},
};
}
self
}
我得到这个错误:
enter code hereerror[E0382]: use of moved value: `self`
--> src/lib.rs:60:26
|
60 | 'A' => { self.advance(); },
| ^^^^ value moved here in previous iteration of loop
|
= note: move occurs because `self` has type `Robot`, which does not implement the `Copy` trait
error[E0382]: use of moved value: `self`
--> src/lib.rs:61:26
|
60 | 'A' => { self.advance(); },
| ---- value moved here
61 | 'R' => { self.turn_right(); },
| ^^^^ value used here after move
|
= note: move occurs because `self` has type `Robot`, which does not implement the `Copy` trait
我认为我收到错误是因为advance() 返回self,但我不明白为什么在块内使用该值时仍会移动该值。我真的必须实现Copy 还是我错过了终生用例?
【问题讨论】:
-
借钱可以吗?另外,为什么不实现
Copy? -
不要实现
Copy,而是阅读the builder pattern -
@EliSadoff 我实际上是在尝试学习如何编写好的代码。我认为在这里复制会很糟糕,因为它会占用不必要的资源。
-
@wimh:代码构造看起来与我尝试构建的相似,但我没有在其中找到答案。谢谢你的链接,顺便说一句,这个页面似乎充满了很棒的东西。