迭代切片的值而不是 Rust 中的引用? [英] Iterating over a slice's values instead of references in Rust?
本文介绍了迭代切片的值而不是 Rust 中的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当循环一个结构片段时,我得到的值是一个引用(这很好),但是在某些情况下,必须将 var
写为 (*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);
}
然而,这只适用于Copy
-types!如果你有一个没有实现 Copy
但实现了 Clone
的类型,你可以使用 cloned()
迭代器适配器;有关详细信息,请参阅 Chris Emerson 的回答.
However, this only works for Copy
-types! If you have a type that doesn't implement Copy
but does implement Clone
, you could use the cloned()
iterator adapter; see Chris Emerson's answer for more information.
这篇关于迭代切片的值而不是 Rust 中的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文