Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

rust - "cannot move out of borrowed context" and "use of moved 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 later 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 the error:

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've read about Rust ownership and borrowing, but I still don't really understand them, therefore I cannot fix this code. Could someone give me a working variant of what I pasted?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As the error message says:

dir moved here because it has type foo::Direction, which is non-copyable

No type is copyable by default, the author has to opt into the marker trait Copy. You almost certainly want Direction to be copyable, so add #[derive(Copy)] to the definition. Point can probably be Copy as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...