循环时,.iter()与引用(&)有何不同? [英] When looping, how does .iter() differ from a reference (&)?

查看:67
本文介绍了循环时,.iter()与引用(&)有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在玩Rust时,我发现您可以通过引用遍历Vec s和HashMap s(可能还有其他),而不是使用.iter().

While playing with Rust, I discovered that you can loop over Vecs and HashMaps (and probably others) by reference, instead of using .iter().

let xs = vec![1, 2, 3, 4, 5];
for x in &xs {
    println!("x == {}", x);
}

.iter()函数似乎具有相同的行为.

The .iter() function seems to have the same behavior.

let xs = vec![1, 2, 3, 4, 5];
for x in xs.iter() {
    println!("x == {}", x);
}

这两种在集合上循环的方法在功能上是否相同,或者两者的行为方式之间是否存在细微的差异?我注意到.iter()似乎是我发现的示例中普遍喜欢的方法.

Are both methods of looping over a collection functionally identical, or are there subtle differences between how the two behave? I notice that .iter() seems to be the universally preferred approach in examples that I've found.

推荐答案

两种遍历功能相同的集合的方法都是

Are both methods of looping over a collection functionally identical

是的,它们是相同的.

IntoIterator表示&Vec<T> :

impl<'a, T> IntoIterator for &'a Vec<T> {
    type Item = &'a T;
    type IntoIter = slice::Iter<'a, T>;

    fn into_iter(self) -> slice::Iter<'a, T> {
        self.iter()
    }
}

IntoIterator对于&HashMap<K, V, S> 的实现:

The implementation of IntoIterator for &HashMap<K, V, S>:

impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
    where K: Eq + Hash, S: HashState
{
    type Item = (&'a K, &'a V);
    type IntoIter = Iter<'a, K, V>;

    fn into_iter(self) -> Iter<'a, K, V> {
        self.iter()
    }
}

请注意,两个都只调用iter().

Note that both just call iter().

我注意到,在发现的示例中,.iter()似乎是普遍首选的方法.

I notice that .iter() seems to be the universally preferred approach in examples that I've found.

每当我想使用迭代器适配器时,就使用collection.iter();每当我想直接对集合进行直接迭代时,就使用&collection.

I use collection.iter() whenever I want to use an iterator adapter, and I use &collection whenever I want to just iterate directly on the collection.

这篇关于循环时,.iter()与引用(&amp;)有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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