不能脱离取消引用(由于索引而取消引用)

时间:2014-12-26 16:05:20

标签: pointers compiler-errors rust

我正在学习Rust并编写简单的游戏。但是有一个错误。有一个Character(s)(enum)向量,当试图返回值(向量的某个索引处的值)时,编译器会显示以下错误

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

1 个答案:

答案 0 :(得分:4)

以下是您的问题的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中,你不能无所畏惧地复制东西,你必须将项目标记为Copy能够。这告诉Rust,对该项进行逐位复制是安全的:

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

这允许MCVE编译。

如果您的商品不是 Copy怎么办?那么引用你的价值是唯一安全的:

let c = &field[0];