问题描述
比方说,我有矢量,我只想保留偶数元素.我将需要使用cloned()
和filter()
.例如:
Let's say that I have vector and I want just keep the even elements. I would need to used cloned()
and filter()
. For example:
fn main() {
let my_vec: Vec<i32> = vec![1,2,3,4];
let my_vec_1: Vec<i32> = my_vec.iter().cloned().filter(|&x| x % 2 == 0).collect();
println!("{:?}", my_vec_1);
let my_vec_2: Vec<i32> = my_vec.iter().filter(|&x| x % 2 == 0).cloned().collect();
println!("{:?}", my_vec_2);
}
两种方法都能奏效.在filter()
之后使用cloned()
似乎更有效率.因为那样,我不必将迭代器的所有元素都从&T
转换为T
,而只需将已过滤的元素转换即可.在我的示例中,这只是元素的一半.
Both approaches work. Using cloned()
after filter()
seems a little bit more efficient. Because then I don't have to convert all elements of the iterator from &T
to T
, but only the ones that have been filtered. In my example that's half the elements.
但是,我似乎看到在filter()
之前应用了cloned()
.这是一个示例: method.inspect
However, I seem to see cloned()
applied before filter()
. Here is one example: method.inspect
我认为对于没有实现Copy
特征的类型,也许必须先使用.cloned()
,但是事实并非如此:嵌套的vec示例.另外,由于过滤器使用FnMut(&Self::Item)
,所以我认为这应该不是问题.
I thought that maybe .cloned()
has to be used before for types that don't implement Copy
trait, but it does not seem to be the case: nested vec example. Also, because filter uses FnMut(&Self::Item)
, I don' think that should be a problem.
在filter()
之前使用cloned()
有优势吗?这更多是风格问题吗?如果是这样,有没有首选的风格?
Are there advantages to using cloned()
before filter()
? Is this more of a stylistic issue? If so, is there preferred style?
推荐答案
这与样式无关.
以inspect
的示例为例来说明inspect
.它以愚蠢的方式使用.cloned
,但之所以选择cloned
是因为其易于理解的语义,从而创建了易于理解的复杂迭代器序列".
The example of inspect
is made to show-case inspect
, that is all. It uses .cloned
in an arguably silly way, but cloned
was probably chosen because of its easy to understand semantic so as to create an easy to understand "complex iterator sequence".
那么,.cloned()
在.filter(...)
之前还是之后?正如您提到的那样,除非克隆对于过滤是必需的(这令人惊讶),否则经验法则是在克隆之后再进行克隆,以最大程度地减少克隆元素的数量.
So, .cloned()
before or after .filter(...)
? As you mention, unless cloning is necessary for filtering (which would be surprising) the rule of thumb will be to clone after so as to minimize the number of cloned elements.
这里没有风格,只是一个务实的绩效评估.
No style here, just a pragmatic performance assessment.
这篇关于.cloned()应该在.filter()之前还是之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!