@@ -312,4 +312,59 @@ pub trait Iterator<T> {
312
312
) -> Zip <T , UIntoIter :: IntoIter > {
313
313
zipped_iterator (self , other . into_iter ())
314
314
}
315
+
316
+ /// Transforms an iterator into a collection.
317
+ ///
318
+ /// `collect()` can take anything iterable, and turn it into a relevant
319
+ /// collection. This is one of the more powerful methods in the core
320
+ /// library, used in a variety of contexts.
321
+ ///
322
+ /// The most basic pattern in which `collect()` is used is to turn one
323
+ /// collection into another. You take a collection, call [`iter`] on it,
324
+ /// do a bunch of transformations, and then `collect()` at the end.
325
+ ///
326
+ /// `collect()` can also create instances of types that are not typical
327
+ /// collections.
328
+ ///
329
+ /// Because `collect()` is so general, it can cause problems with type
330
+ /// inference. As such, `collect()` is one of the few times you'll see
331
+ /// the syntax affectionately known as the 'turbofish': `::<>`. This
332
+ /// helps the inference algorithm understand specifically which collection
333
+ /// you're trying to collect into.
334
+ ///
335
+ /// # Examples
336
+ ///
337
+ /// Basic usage:
338
+ ///
339
+ /// ```
340
+ /// let doubled: Array<u32> = array![1, 2, 3].into_iter().map(|x| x * 2).collect();
341
+ ///
342
+ /// assert_eq!(array![2, 4, 6], doubled);
343
+ /// ```
344
+ ///
345
+ /// Note that we needed the `: Array<u32>` on the left-hand side.
346
+ ///
347
+ /// Using the 'turbofish' instead of annotating `doubled`:
348
+ ///
349
+ /// ```
350
+ /// let doubled = array![1, 2, 3].into_iter().map(|x| x * 2).collect::<Array<u32>>();
351
+ ///
352
+ /// assert_eq!(array![2, 4, 6], doubled);
353
+ /// ```
354
+ ///
355
+ /// Because `collect()` only cares about what you're collecting into, you can
356
+ /// still use a partial type hint, `_`, with the turbofish:
357
+ ///
358
+ /// ```
359
+ /// let doubled = array![1, 2, 3].into_iter().map(|x| x * 2).collect::<Array<_>>();
360
+ ///
361
+ /// assert_eq!(array![2, 4, 6], doubled);
362
+ /// ```
363
+ #[inline]
364
+ #[must_use]
365
+ fn collect <B , + FromIterator <B , Self :: Item >, + Destruct <T >>(
366
+ self : T ,
367
+ ) -> B {
368
+ FromIterator :: <B , Self :: Item >:: from_iter :: <T , Self >(self )
369
+ }
315
370
}
0 commit comments