"cannot move out of borrowed context"和"use of moved value"



我有以下代码:

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 所有权和借用的信息,但我仍然不真正理解它们,因此我无法修复此代码。有人可以给我粘贴的内容的工作变体吗?

正如错误消息所说:

dir移到这里,因为它有类型 foo::Direction ,这是不可复制的

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

相关内容

  • 没有找到相关文章

最新更新