对于代码:
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 编译而来的。
最佳答案
默认情况下移动匹配案例中的变量。不允许移动 x
,因为循环中的所有内容都是不可变的。要获取对 x
str 的引用,您需要使用 ref
关键字:
&Baz(ref x) => *x == ~"asdf"
关于rust - 在 for 循环中使用拥有的指针访问枚举的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18049723/