"cannot get out of the borrowed context" and "use the transferred value",

I have the following code:

pub enum Direction { Up, Right, Down, Left, None } struct Point { y: i32, x: i32 } pub struct Chain { segments: Vec<Point>, direction: Direction } 

and then I implement the following function:

 fn turn (&mut self, dir: Direction) -> i32 { use std::num::SignedInt; if dir == self.direction { return 0; } else if SignedInt::abs(dir as i32 - self.direction as i32) == 2 { return -1; } else { self.direction = dir; return 1; } } 

I get an error message:

 error: cannot move out of borrowed content foo.rs:45 else if SignedInt::abs(dir as i32 - self.direction as i32) == 2 { return 1; } ^~~~ foo.rs:47:21: 47:24 error: use of moved value: `dir` foo.rs:47 self.direction = dir; ^~~ foo.rs:45:26: 45:29 note: `dir` moved here because it has type `foo::Direction`, which is non-copyable foo.rs:45 else if SignedInt::abs(dir as i32 - self.direction as i32) == 2 { return 1; } 

I read about Rust's ownership and borrowing, but I still don't understand them, so I can't fix this code. Can someone give me a working version of what I inserted?

+1
source share
1 answer

As the error message says:

dir moved here because it is of type foo::Direction , which is not copied

No type is copied by default, the author should choose the marker marker Copy . You almost certainly want Direction be copied, so add #[derive(Copy)] to the definition. Point may possibly be Copy .

+3
source

All Articles