Skip to content

Commit

Permalink
doc: Iterator::collect
Browse files Browse the repository at this point in the history
  • Loading branch information
julio4 committed Jan 20, 2025
1 parent 3b44f0e commit a0a82a8
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions corelib/src/iter/traits/iterator.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,53 @@ pub trait Iterator<T> {
zipped_iterator(self, other.into_iter())
}

/// Transforms an iterator into a collection.
///
/// `collect()` can take anything iterable, and turn it into a relevant
/// collection. This is one of the more powerful methods in the core
/// library, used in a variety of contexts.
///
/// The most basic pattern in which `collect()` is used is to turn one
/// collection into another. You take a collection, call [`iter`] on it,
/// do a bunch of transformations, and then `collect()` at the end.
///
/// `collect()` can also create instances of types that are not typical
/// collections.
///
/// Because `collect()` is so general, it can cause problems with type
/// inference. As such, `collect()` is one of the few times you'll see
/// the syntax affectionately known as the 'turbofish': `::<>`. This
/// helps the inference algorithm understand specifically which collection
/// you're trying to collect into.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let doubled: Array<u32> = array![1, 2, 3].into_iter().map(|x| x * 2).collect();
///
/// assert_eq!(array![2, 4, 6], doubled);
/// ```
///
/// Note that we needed the `: Array<u32>` on the left-hand side.
///
/// Using the 'turbofish' instead of annotating `doubled`:
///
/// ```
/// let doubled = array![1, 2, 3].into_iter().map(|x| x * 2).collect::<Array<u32>>();
///
/// assert_eq!(array![2, 4, 6], doubled);
/// ```
///
/// Because `collect()` only cares about what you're collecting into, you can
/// still use a partial type hint, `_`, with the turbofish:
///
/// ```
/// let doubled = array![1, 2, 3].into_iter().map(|x| x * 2).collect::<Array<_>>();
///
/// assert_eq!(array![2, 4, 6], doubled);
/// ```
#[inline]
#[must_use]
fn collect<B, +FromIterator<B, Self::Item>, +Destruct<T>>(
Expand Down

0 comments on commit a0a82a8

Please sign in to comment.