- Mastering Rust
- Rahul Sharma Vesa Kaihlavirta
- 369字
- 2021-07-02 13:35:18
Iterators
An iterator is a construct that provides an efficient way to act on elements of collection types. They are not a new concept, though. In many imperative languages, they are implemented as objects that are constructed from collection types such as lists or maps. For instance, Python's iter(some_list) or C++'s vector.begin() are ways to construct iterators from an existing collection. The main motivation for iterators to exist in the first place is that they provide a higher level abstraction of walking through items of a collection instead of using manual for loops, which are very much prone to off by one errors. Another advantage is that iterators do not read the whole collection in memory and are lazy. By lazy, we mean that the iterator only evaluates or accesses an element in a collection when needed. Iterators can also be chained with multiple transformation operations, such as filtering elements based on a condition, and do not evaluate the transformations until you need them. To access these items when you need them, iterators provide a next() method, which tries to read the next item from the collection. This occurs when the iterator evaluates the chain of computation.
In Rust, an iterator is any type that implements the Iterator trait. This type can then be used in a for loop to walk over its items. They are implemented for most standard library collection types such as Vector, HashMap, BTreeMap, and many more and one can also implement it for their own types.
Iterators are frequently used whenever we are dealing with collection types in Rust. In fact, Rust's for loop is desugared into a normal match expression with next calls on the object being iterated over. Also, we can convert most collection types into an iterator by calling iter() or into_iter() on them. That's enough information on iterators – now, we can tackle the following exercise. We'll go deep into iterators and implement one ourselves in Chapter 7, Advanced Concepts.
- 國際大學(xué)生程序設(shè)計競賽中山大學(xué)內(nèi)部選拔真題解(二)
- 軟件項目管理(第2版)
- HTML5入門經(jīng)典
- 劍指Java:核心原理與應(yīng)用實踐
- Oracle 18c 必須掌握的新特性:管理與實戰(zhàn)
- AIRIOT物聯(lián)網(wǎng)平臺開發(fā)框架應(yīng)用與實戰(zhàn)
- Django 3.0入門與實踐
- Software Development on the SAP HANA Platform
- 百萬在線:大型游戲服務(wù)端開發(fā)
- UI動效設(shè)計從入門到精通
- Android 5從入門到精通
- BackTrack 5 Cookbook
- 軟件自動化測試實戰(zhàn)解析:基于Python3編程語言
- PHP從入門到精通(微視頻精編版)
- Learning Ext JS(Fourth Edition)