내가 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
}
I을 이 오류를 얻을 :
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'를 구현하지 말고 [빌더 패턴] (https://aturon.github.io/ownership/builders.html)을 읽으십시오. – wimh
@EliSadoff 실제로 좋은 코드를 작성하는 방법을 배우려고합니다. 나는 불필요하게 자원을 필요로하기 때문에 여기서 복사하는 것이 좋지 않을 것이라고 생각한다. – stamm