2013-08-05 31 views
2

的代碼:與擁有指針訪問一個枚舉的內容在for循環中

enum A { 
    Foo, 
    Bar, 
    Baz(~str) 
} 

#[test] 
fn test_vector(){ 
    let test_vec = ~[Foo, Bar, Baz(~"asdf")]; 

    for x in test_vec.iter() { 
     match x { 
      &Foo => true, 
      &Bar => true, 
      &Baz(x) => x == ~"asdf" 
     }; 
    } 
} 

我收到以下錯誤:

stackoverflow.rs:15:13: 15:19 error: cannot move out of dereference of & pointer 
stackoverflow.rs:15    &Baz(x) => x == ~"asdf" 
          ^~~~~~ 
error: aborting due to previous error 

如果我改變字符串爲int它編譯好。

我的問題是:如何訪問for循環中枚舉中的擁有指針的內容?有沒有我應該使用的替代迭代器?

我使用的Rust版本是由master編譯的。

+2

我不靠近我的電腦,和0.7無法安裝這檯筆記本電腦,但我想你應該嘗試'&巴茲(REF X)' 。 –

回答

1

默認情況下會移動匹配項中的變量。您不得移動x,因爲循環中的所有內容都是不可變的。要得到x基準海峽你需要使用ref關鍵字:

&Baz(ref x) => *x == ~"asdf" 
+1

請注意asdf「== * x'或'x.as_slice()== asdf」'會更有效率,因爲它們沒有分配。 (不可能只寫'* x ==「asdf」'被視爲一個bug。) – huon