假设我有一些函数
do_stuff
需要一个 &HashSet<X>
并希望通过复制所有元素将项目收集到 Vec<X>
中。做到这一点的规范方法是什么?我基本上找到了以下方法来做到这一点:
使用
_.clone().into_iter().collect()
(GodBolt Link):
use std::collections::HashSet;
#[derive(Copy, Clone, Eq, Hash, PartialEq)]
struct X {}
struct Y {
xs: HashSet<X>,
}
fn do_stuff(y: &Y) -> Vec<X> {
y.xs.clone().into_iter().collect()
}
这里推荐这个:
使用
_.iter().cloned().collect()
(GodBolt Link):
use std::collections::HashSet;
#[derive(Copy, Clone, Eq, Hash, PartialEq)]
struct X {}
struct Y {
xs: HashSet<X>,
}
fn do_stuff(y: &Y) -> Vec<X> {
y.xs.iter().cloned().collect()
}
这里推荐这个:
使用
Vec::from_iter(_.iter().cloned())
(GodBolt Link):
use std::collections::HashSet;
#[derive(Copy, Clone, Eq, Hash, PartialEq)]
struct X {}
struct Y {
xs: HashSet<X>,
}
fn do_stuff(y: &Y) -> Vec<X> {
Vec::from_iter(y.xs.iter().cloned())
}
这里推荐这个:
我有两个问题:
以上方法有什么本质区别?
将
&HashSet<X>
中的物品收集到 Vec<X>
中的规范方法是什么?
相关:
_.clone().into_iter().collect()
此创建
HashSet
的中间副本。这不是你想要的,它是不必要的分配和处理。经验法则是:更喜欢 .cloned()
而不是 .clone()
。
这两个:
_.iter().cloned().collect()
Vec::from_iter(_.iter().cloned())
是等价的。在我看来,第一个更具可读性。