๐Ÿ”ƒ Rust Iterators

= a value that produces a sequence of values, typically for a loop to operate on1

Usage

1. Iterator creation

Structs
  • std::iter::IntoIter:.into_iter() -> returns an Iterator
    • takes collection by value and consumes it
  • .drain()
    • borrows mut ref to collection, removes remaining entries on exit
Ranges
  • (1..=n)
Functions
  1. Specify function
    • from_fn(f): creates an iterator from a function
    • successors(Some(start_val), f): like reduce from JS for functions

2. Value processing

To avoid value consumption (which is standard for most adapters):

  • by_ref() -> returns iterator as a reference
Adapters

Adapters are functions, which can be called on an iterator and return a new iterator

  • .map(f): maps each value using f
  • filter(f): filters each value using f
  • filter_map(f): like .map() but also allows returning zero items
  • flat_map(f): like .filter_map(f), but allows returning multiple items
  • flatten(): concatenates all iterable items
    • e.g: [[1, 1.1], [2, 2.2]] -> [1, 1.1, 2, 2.2]
    • used to get all Some(val) from an array of None/Some
Other
  • fuse() -> transforms iterator into one that definitely returns None when last element reached
  • inspect(f): doesnโ€™t do anything other than calling f, used for debugging
  • chain(i): chains two iterators together
    • e.g.: i1.chain(i2) -> iterator that iterates over i1 and then i2
  • zip(i):: zips two iterators together
    • e.g.: i1.zip(i2) -> returns pairs with (item1, item2)
  • repeat(item): iterator that always returns item
  • cycle(iterable): iterator that always iterates over iterable
  • enumerate(): return pairs with (index, item) instead of just item
Iteration
  • .take(n): limits iterator calls to n
  • take_while(f): end iteration when f = true
  • skip(n): skips first n items
  • skip_while(f): skips items while f = true
  • peek(): returns Option containing next item (or None)
    • doesnโ€™t take ownership

3. Value consumption

Called at the end of an iterator process, this is the value thatโ€™s returned

  • count(): returns the count of items in the iterator
  • sum(), product(): returns the sum/product of all items in the iterator (must be integers/floats)
  • max(), min(): returns max/min item (implementing std::cmp::Ord)
  • max_by(f), min_by(f): returns max/min as determined by f, comparator function returning std::cmp::Ordering
  • max_by_key(f), min_by_key(f): returns max/min as determined by f, a closure returning an option
  • fold(): like .reduce from JS
    • e.g.: y = (1..=n).fold(0, |x| ...)
      • start with 0 as running total
      • continue value of closure, until end reached
      • returns final value of closure
  • nth(n), nth_back(n): skipos n items, returns next item
  • collect(): returns a collections from the iterator (e.g. Vector)

Definitions

Traits

  • std::iter::Iterator: any value that implements this trait is an iterator
    • -> produces values = items
    • -> items are recieved by consumers
  • std::iter::IntoIter: value that implements this trait is an iterable
    • for is just shorthand for into_iter

Functions

  • .fold: like .reduce from JS

    • e.g.: y = (1..=n).fold(0, |x| ...)
      • start with 0 as running total
      • continue value of closure, until end reached
      • returns final value of closure
  • from_fn(f): creates an iterator from a function

  • successors(Some(start_val), f): like reduce from JS

  • .take(n): limits iterator calls to n

  • .collect(): builds a vector from the iterator results

Footnotes

  1. Programming Rust, 2nd Edition. Accessed April 5, 2022. https://learning.oreilly.com/library/view/programming-rust-2nd/9781492052586/. โ†ฉ