gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:14:51 24 4
gpt4 key购买 nike

我有以下代码:

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 moved here because it has type foo::Direction, which is non-copyable

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

关于rust - "cannot move out of borrowed context"和 "use of moved value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28527702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com