rust - 在 for 循环中使用拥有的指针访问枚举的内容

标签 rust

对于代码:

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/

相关文章:

rust - 从前端包中的包引用 Gfx 后端类型

python - 如何使用 Rust 使用默认程序启动任何文件(如 Python 的 `os.startfile()` )

websocket - 为变形过滤器重用已移动的变量

syntax - 为什么将特征作为函数参数传递时需要 `impl`?

arrays - 如何在 RUST 中逐字节比较 2 个不同的字符串文字

caching - Rust 中的安全缓存无需重新计数

rust - 带有 eq_any 的子查询无法编译

rust - 为什么 Dbg 似乎不能在 for_each 循环中工作?

javascript - JavaScript 应用程序拒绝向 Rust Rocket 服务器发出错误连接请求

rust - 为什么这个模式无法到达?