迭代切片的值而不是Rust中的引用? [英] Iterating over a slice's values instead of references in Rust?

查看:276
本文介绍了迭代切片的值而不是Rust中的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当循环遍历一片结构时,我得到的值是一个引用(很好),但在某些情况下,必须将 var 写为<在许多地方code>(* var)。

When looping over a slice of structs, the value I get is a reference (which is fine), however in some cases it's annoying to have to write var as (*var) in many places.

有没有更好的方法来避免重新声明变量?

Is there a better way to avoid re-declaring the variable?

fn my_fn(slice: &[MyStruct]) {
    for var in slice {
        let var = *var;  // <-- how to avoid this?

        // Without the line above, errors in comments occur:

        other_fn(var);  // <-- expected struct `MyStruct`, found reference

        if var != var.other {
            // ^^ trait `&MyStruct: std::cmp::PartialEq<MyStruct>>` not satisfied
            foo();
        }
    }
}






请参阅:实际错误输出(更加神秘)。

推荐答案

您可以在模式

//  |
//  v
for &var in slice {
    other_fn(var);
}

然而,这仅适用于 复制 -types !如果你有非复制,但克隆 -only类型,你可以使用 cloned()迭代器适配器;有关更多信息,请参阅Chris Emerson的答案。如果您的类型不是克隆,则您没有机会这样做。

However, this only works for Copy-types! If you have non-Copy, but Clone-only types, you could use the cloned() iterator adapter; see Chris Emerson's answer for more information. If you have types that aren't Clone, you have no chance to do it.

这篇关于迭代切片的值而不是Rust中的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆