【问题标题】:cannot move out of dereference (dereference is implicit due to indexing)不能移出取消引用(由于索引,取消引用是隐式的)
【发布时间】:2014-12-26 16:05:19
【问题描述】:

我目前正在学习 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

main.rs:

mod field;

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

field.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
    }
}

【问题讨论】:

标签: pointers compiler-errors rust


【解决方案1】:

这是针对您的问题的 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 编译。

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

let c = &field[0];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 2016-11-18
    • 2022-01-17
    • 2023-03-09
    • 1970-01-01
    • 2014-10-12
    相关资源
    最近更新 更多