2014-12-26 43 views
2

我目前正在學習Rust並編寫簡單的遊戲。但是有一個錯誤。有字符(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 
    } 
} 
+0

歡迎來到堆棧溢出!將來,您應該嘗試創建[最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve)。這有助於我們更快地回答您的問題,並可能幫助您自己解決問題! – Shepmaster

回答

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