]>
git.proxmox.com Git - rustc.git/blob - library/core/src/iter/traits/collect.rs
1 /// Conversion from an [`Iterator`].
3 /// By implementing `FromIterator` for a type, you define how it will be
4 /// created from an iterator. This is common for types which describe a
5 /// collection of some kind.
7 /// If you want to create a collection from the contents of an iterator, the
8 /// [`Iterator::collect()`] method is preferred. However, when you need to
9 /// specify the container type, [`FromIterator::from_iter()`] can be more
10 /// readable than using a turbofish (e.g. `::<Vec<_>>()`). See the
11 /// [`Iterator::collect()`] documentation for more examples of its use.
13 /// See also: [`IntoIterator`].
20 /// let five_fives = std::iter::repeat(5).take(5);
22 /// let v = Vec::from_iter(five_fives);
24 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
27 /// Using [`Iterator::collect()`] to implicitly use `FromIterator`:
30 /// let five_fives = std::iter::repeat(5).take(5);
32 /// let v: Vec<i32> = five_fives.collect();
34 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
37 /// Using [`FromIterator::from_iter()`] as a more readable alternative to
38 /// [`Iterator::collect()`]:
41 /// use std::collections::VecDeque;
42 /// let first = (0..10).collect::<VecDeque<i32>>();
43 /// let second = VecDeque::from_iter(0..10);
45 /// assert_eq!(first, second);
48 /// Implementing `FromIterator` for your type:
51 /// // A sample collection, that's just a wrapper over Vec<T>
53 /// struct MyCollection(Vec<i32>);
55 /// // Let's give it some methods so we can create one and add things
57 /// impl MyCollection {
58 /// fn new() -> MyCollection {
59 /// MyCollection(Vec::new())
62 /// fn add(&mut self, elem: i32) {
63 /// self.0.push(elem);
67 /// // and we'll implement FromIterator
68 /// impl FromIterator<i32> for MyCollection {
69 /// fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
70 /// let mut c = MyCollection::new();
80 /// // Now we can make a new iterator...
81 /// let iter = (0..5).into_iter();
83 /// // ... and make a MyCollection out of it
84 /// let c = MyCollection::from_iter(iter);
86 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
88 /// // collect works too!
90 /// let iter = (0..5).into_iter();
91 /// let c: MyCollection = iter.collect();
93 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
95 #[stable(feature = "rust1", since = "1.0.0")]
96 #[rustc_on_unimplemented(
99 message
= "a value of type `{Self}` cannot be built since `{Self}` has no definite size",
100 label
= "try explicitly collecting into a `Vec<{A}>`",
120 message
= "a value of type `{Self}` cannot be built since `{Self}` has no definite size",
121 label
= "try explicitly collecting into a `Vec<{A}>`",
123 message
= "a value of type `{Self}` cannot be built from an iterator \
124 over elements of type `{A}`",
125 label
= "value of type `{Self}` cannot be built from `std::iter::Iterator<Item={A}>`"
127 #[rustc_diagnostic_item = "FromIterator"]
128 pub trait FromIterator
<A
>: Sized
{
129 /// Creates a value from an iterator.
131 /// See the [module-level documentation] for more.
133 /// [module-level documentation]: crate::iter
140 /// let five_fives = std::iter::repeat(5).take(5);
142 /// let v = Vec::from_iter(five_fives);
144 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
146 #[stable(feature = "rust1", since = "1.0.0")]
147 fn from_iter
<T
: IntoIterator
<Item
= A
>>(iter
: T
) -> Self;
150 /// Conversion into an [`Iterator`].
152 /// By implementing `IntoIterator` for a type, you define how it will be
153 /// converted to an iterator. This is common for types which describe a
154 /// collection of some kind.
156 /// One benefit of implementing `IntoIterator` is that your type will [work
157 /// with Rust's `for` loop syntax](crate::iter#for-loops-and-intoiterator).
159 /// See also: [`FromIterator`].
166 /// let v = [1, 2, 3];
167 /// let mut iter = v.into_iter();
169 /// assert_eq!(Some(1), iter.next());
170 /// assert_eq!(Some(2), iter.next());
171 /// assert_eq!(Some(3), iter.next());
172 /// assert_eq!(None, iter.next());
174 /// Implementing `IntoIterator` for your type:
177 /// // A sample collection, that's just a wrapper over Vec<T>
179 /// struct MyCollection(Vec<i32>);
181 /// // Let's give it some methods so we can create one and add things
183 /// impl MyCollection {
184 /// fn new() -> MyCollection {
185 /// MyCollection(Vec::new())
188 /// fn add(&mut self, elem: i32) {
189 /// self.0.push(elem);
193 /// // and we'll implement IntoIterator
194 /// impl IntoIterator for MyCollection {
196 /// type IntoIter = std::vec::IntoIter<Self::Item>;
198 /// fn into_iter(self) -> Self::IntoIter {
199 /// self.0.into_iter()
203 /// // Now we can make a new collection...
204 /// let mut c = MyCollection::new();
206 /// // ... add some stuff to it ...
211 /// // ... and then turn it into an Iterator:
212 /// for (i, n) in c.into_iter().enumerate() {
213 /// assert_eq!(i as i32, n);
217 /// It is common to use `IntoIterator` as a trait bound. This allows
218 /// the input collection type to change, so long as it is still an
219 /// iterator. Additional bounds can be specified by restricting on
223 /// fn collect_as_strings<T>(collection: T) -> Vec<String>
226 /// T::Item: std::fmt::Debug,
230 /// .map(|item| format!("{item:?}"))
234 #[rustc_diagnostic_item = "IntoIterator"]
235 #[rustc_skip_array_during_method_dispatch]
236 #[stable(feature = "rust1", since = "1.0.0")]
237 pub trait IntoIterator
{
238 /// The type of the elements being iterated over.
239 #[stable(feature = "rust1", since = "1.0.0")]
242 /// Which kind of iterator are we turning this into?
243 #[stable(feature = "rust1", since = "1.0.0")]
244 type IntoIter
: Iterator
<Item
= Self::Item
>;
246 /// Creates an iterator from a value.
248 /// See the [module-level documentation] for more.
250 /// [module-level documentation]: crate::iter
257 /// let v = [1, 2, 3];
258 /// let mut iter = v.into_iter();
260 /// assert_eq!(Some(1), iter.next());
261 /// assert_eq!(Some(2), iter.next());
262 /// assert_eq!(Some(3), iter.next());
263 /// assert_eq!(None, iter.next());
265 #[lang = "into_iter"]
266 #[stable(feature = "rust1", since = "1.0.0")]
267 fn into_iter(self) -> Self::IntoIter
;
270 #[stable(feature = "rust1", since = "1.0.0")]
271 impl<I
: Iterator
> IntoIterator
for I
{
276 fn into_iter(self) -> I
{
281 /// Extend a collection with the contents of an iterator.
283 /// Iterators produce a series of values, and collections can also be thought
284 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
285 /// to extend a collection by including the contents of that iterator. When
286 /// extending a collection with an already existing key, that entry is updated
287 /// or, in the case of collections that permit multiple entries with equal
288 /// keys, that entry is inserted.
295 /// // You can extend a String with some chars:
296 /// let mut message = String::from("The first three letters are: ");
298 /// message.extend(&['a', 'b', 'c']);
300 /// assert_eq!("abc", &message[29..32]);
303 /// Implementing `Extend`:
306 /// // A sample collection, that's just a wrapper over Vec<T>
308 /// struct MyCollection(Vec<i32>);
310 /// // Let's give it some methods so we can create one and add things
312 /// impl MyCollection {
313 /// fn new() -> MyCollection {
314 /// MyCollection(Vec::new())
317 /// fn add(&mut self, elem: i32) {
318 /// self.0.push(elem);
322 /// // since MyCollection has a list of i32s, we implement Extend for i32
323 /// impl Extend<i32> for MyCollection {
325 /// // This is a bit simpler with the concrete type signature: we can call
326 /// // extend on anything which can be turned into an Iterator which gives
327 /// // us i32s. Because we need i32s to put into MyCollection.
328 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
330 /// // The implementation is very straightforward: loop through the
331 /// // iterator, and add() each element to ourselves.
332 /// for elem in iter {
338 /// let mut c = MyCollection::new();
344 /// // let's extend our collection with three more numbers
345 /// c.extend(vec![1, 2, 3]);
347 /// // we've added these elements onto the end
348 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{c:?}"));
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub trait Extend
<A
> {
352 /// Extends a collection with the contents of an iterator.
354 /// As this is the only required method for this trait, the [trait-level] docs
355 /// contain more details.
357 /// [trait-level]: Extend
364 /// // You can extend a String with some chars:
365 /// let mut message = String::from("abc");
367 /// message.extend(['d', 'e', 'f'].iter());
369 /// assert_eq!("abcdef", &message);
371 #[stable(feature = "rust1", since = "1.0.0")]
372 fn extend
<T
: IntoIterator
<Item
= A
>>(&mut self, iter
: T
);
374 /// Extends a collection with exactly one element.
375 #[unstable(feature = "extend_one", issue = "72631")]
376 fn extend_one(&mut self, item
: A
) {
377 self.extend(Some(item
));
380 /// Reserves capacity in a collection for the given number of additional elements.
382 /// The default implementation does nothing.
383 #[unstable(feature = "extend_one", issue = "72631")]
384 fn extend_reserve(&mut self, additional
: usize) {
389 #[stable(feature = "extend_for_unit", since = "1.28.0")]
390 impl Extend
<()> for () {
391 fn extend
<T
: IntoIterator
<Item
= ()>>(&mut self, iter
: T
) {
392 iter
.into_iter().for_each(drop
)
394 fn extend_one(&mut self, _item
: ()) {}
397 #[stable(feature = "extend_for_tuple", since = "1.56.0")]
398 impl<A
, B
, ExtendA
, ExtendB
> Extend
<(A
, B
)> for (ExtendA
, ExtendB
)
403 /// Allows to `extend` a tuple of collections that also implement `Extend`.
405 /// See also: [`Iterator::unzip`]
409 /// let mut tuple = (vec![0], vec![1]);
410 /// tuple.extend([(2, 3), (4, 5), (6, 7)]);
411 /// assert_eq!(tuple.0, [0, 2, 4, 6]);
412 /// assert_eq!(tuple.1, [1, 3, 5, 7]);
414 /// // also allows for arbitrarily nested tuples as elements
415 /// let mut nested_tuple = (vec![1], (vec![2], vec![3]));
416 /// nested_tuple.extend([(4, (5, 6)), (7, (8, 9))]);
418 /// let (a, (b, c)) = nested_tuple;
419 /// assert_eq!(a, [1, 4, 7]);
420 /// assert_eq!(b, [2, 5, 8]);
421 /// assert_eq!(c, [3, 6, 9]);
423 fn extend
<T
: IntoIterator
<Item
= (A
, B
)>>(&mut self, into_iter
: T
) {
425 let iter
= into_iter
.into_iter();
428 a
: &'a
mut impl Extend
<A
>,
429 b
: &'a
mut impl Extend
<B
>,
430 ) -> impl FnMut((), (A
, B
)) + 'a
{
437 let (lower_bound
, _
) = iter
.size_hint();
439 a
.extend_reserve(lower_bound
);
440 b
.extend_reserve(lower_bound
);
443 iter
.fold((), extend(a
, b
));
446 fn extend_one(&mut self, item
: (A
, B
)) {
447 self.0.extend_one(item
.0);
448 self.1.extend_one(item
.1);
451 fn extend_reserve(&mut self, additional
: usize) {
452 self.0.extend_reserve(additional
);
453 self.1.extend_reserve(additional
);