“不能脱离借用的上下文"和“移动价值的使用" [英] "cannot move out of borrowed context" and "use of moved value"

查看:35
本文介绍了“不能脱离借用的上下文"和“移动价值的使用"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

我收到错误:

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 所有权和借用的内容,但我仍然不太了解它们,因此我无法修复此代码.有人能给我一个我粘贴的工作变体吗?

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?

推荐答案

如错误信息所述:

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

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

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

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.

这篇关于“不能脱离借用的上下文"和“移动价值的使用"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆