2016-06-07 144 views
4

當我試圖編譯這段代碼,我得到了E0508​​錯誤:我不明白,錯誤E0508​​

cannot move out of type [Enum; 2] , a non-copy fixed-size array

enum Enum { 
    Val1 = 0, 
    Val2 = 1, 
} 

fn main() { 
    let a = [Enum::Val1, Enum::Val2]; 
    let x: i32 = a[0] as i32 + a[1] as i32; 
    println!("{}", x); 
} 

我只是想從枚舉類型的數組訪問單個值。

+1

爲什麼downvote?請解釋它是一個好主意。 – Boiethios

+3

我沒有倒下,但長期用戶很少解釋downvotes,因爲他們經歷了生氣的OPs報復和投票報復。我認爲大多數人都贊成異或評論。 – Shepmaster

+0

你確定它是'(grid [i] [0])+ grid [i] [1] + grid [i] [2]/3',而不是'(grid [i] [0] + grid [i ] [1] + grid [i] [2])/ 3'? – kennytm

回答

4

較小的再現:

enum Enum { 
    Val1 = 0, 
    Val2 = 1, 
} 

fn main() { 
    let a = [Enum::Val1]; 
    a[0] as i32; 
} 

最簡單的解決方法是讓你的枚舉Copy

#[derive(Copy, Clone)] 
enum Enum { 
    Val1 = 0, 
    Val2 = 1, 
} 

where is the copy needed?

這是一個很好的問題,我不完全知道爲什麼值被強制轉換爲整數時需要移動。這與陣列沒有任何具體關係:

#[derive(Debug)] 
enum Enum { 
    Val1 = 0, 
    Val2 = 1, 
} 

fn main() { 
    let a = Enum::Val1; 
    let b = a as i32; 
    println!("{:?}", a); // Error: a was moved in the line above 
} 
+0

謝謝您的簡約再現,我試圖做到這一點,但仍然有太多的線條:p並且您的解決方案有效。是否有可能通過網格作爲參考,而不是複製它? – Boiethios

+0

@Boiethios *可能通過網格作爲參考* - 你已經這樣做:'&Grid' – Shepmaster

+1

我不明白需要複製的地方? – Boiethios