"无法摆脱借来的背景"和"使用移动值"

时间:2015-02-15 15:29:41

标签: rust

我有以下代码:

pub enum Direction {
    Up, Right, Down, Left, None
}

struct Point {
    y: i32,
    x: i32
}

pub struct Chain {
    segments: Vec<Point>,
    direction: Direction
}

后来我实现了以下功能:

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;
    }
}

我收到错误:

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; }

我已经读过有关Rust所有权和借款的内容,但我仍然不了解它们,因此我无法修复此代码。有人可以给我一个我粘贴的工作变体吗?

1 个答案:

答案 0 :(得分:3)

正如错误消息所示:

  

dir已移至此处,因为其类型为foo::Direction,且不可复制

默认情况下,任何类型都不可复制,作者必须选择标记特征Copy。您几乎肯定希望Direction可以复制,因此请将#[derive(Copy)]添加到定义中。 Point也可能是Copy