gpt4 book ai didi

pointers - 不能移出解除引用(由于索引,解除引用是隐式的)

转载 作者:行者123 更新时间:2023-11-29 08:05:38 27 4
gpt4 key购买 nike

我目前正在学习 Rust 并编写简单的游戏。但是有一个错误。有一个字符向量(枚举),当尝试返回值(向量的某个索引处的值)时,编译器显示以下错误

rustc main.rs
field.rs:29:9: 29:39 error: cannot move out of dereference
(dereference is implicit, due to indexing)
field.rs:29 self.clone().field[index - 1u] as int
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error

主要.rs:

mod field;

fn main() {
let mut field = field::Field::new(3u);
field.change_cell(1, field::Character::X);
println!("{}", field.get_cell(1));
}

字段.rs:

pub enum Character {
NONE, X, O,
}

pub struct Field {
field: Vec<Character>,
size: uint,
cells: uint,
}

impl Field {
pub fn new(new_size: uint) -> Field {
Field {
field: Vec::with_capacity(new_size*new_size),
size: new_size,
cells: new_size*new_size,
}
}

pub fn change_cell(&mut self, cell_number: uint, new_value: Character) -> bool {
...
}

pub fn get_cell(&self, index: uint) -> int {
self.field[index - 1u] as int
}
}

最佳答案

这是针对您的问题的 MCVE:

enum Character {
NONE, X, O,
}

fn main() {
let field = vec![Character::X, Character::O];
let c = field[0];
}

编译此 on the Playpen有这些错误:

error: cannot move out of dereference (dereference is implicit, due to indexing)
let c = field[0];
^~~~~~~~
note: attempting to move value to here
let c = field[0];
^
to prevent the move, use `ref c` or `ref mut c` to capture value by reference
let c = field[0];
^

问题是当您使用索引时,您正在调用 Index trait它返回对向量的引用。此外,还有语法糖可以隐式取消引用该值。这是一件好事,因为人们通常不希望得到引用。

当您将值分配给另一个变量时,您会遇到麻烦。在 Rust 中,你不能随意复制东西,你必须将项目标记为 Copyable。这告诉 Rust 可以安全地逐位复制该项目:

#[derive(Copy,Clone)]
enum Character {
NONE, X, O,
}

这允许 MCVE 编译。

如果您的项目不是Copy怎么办?那么只有引用你的值才是安全的:

let c = &field[0];

关于pointers - 不能移出解除引用(由于索引,解除引用是隐式的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27659274/

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