]> git.lizzy.rs Git - rust.git/blob - library/core/src/iter/traits/collect.rs
Use intra-doc links in core/src/iter when possible
[rust.git] / library / core / src / iter / traits / collect.rs
1 /// Conversion from an [`Iterator`].
2 ///
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.
6 ///
7 /// [`FromIterator::from_iter()`] is rarely called explicitly, and is instead
8 /// used through [`Iterator::collect()`] method. See [`Iterator::collect()`]'s
9 /// documentation for more examples.
10 ///
11 /// See also: [`IntoIterator`].
12 ///
13 /// # Examples
14 ///
15 /// Basic usage:
16 ///
17 /// ```
18 /// use std::iter::FromIterator;
19 ///
20 /// let five_fives = std::iter::repeat(5).take(5);
21 ///
22 /// let v = Vec::from_iter(five_fives);
23 ///
24 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
25 /// ```
26 ///
27 /// Using [`Iterator::collect()`] to implicitly use `FromIterator`:
28 ///
29 /// ```
30 /// let five_fives = std::iter::repeat(5).take(5);
31 ///
32 /// let v: Vec<i32> = five_fives.collect();
33 ///
34 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
35 /// ```
36 ///
37 /// Implementing `FromIterator` for your type:
38 ///
39 /// ```
40 /// use std::iter::FromIterator;
41 ///
42 /// // A sample collection, that's just a wrapper over Vec<T>
43 /// #[derive(Debug)]
44 /// struct MyCollection(Vec<i32>);
45 ///
46 /// // Let's give it some methods so we can create one and add things
47 /// // to it.
48 /// impl MyCollection {
49 ///     fn new() -> MyCollection {
50 ///         MyCollection(Vec::new())
51 ///     }
52 ///
53 ///     fn add(&mut self, elem: i32) {
54 ///         self.0.push(elem);
55 ///     }
56 /// }
57 ///
58 /// // and we'll implement FromIterator
59 /// impl FromIterator<i32> for MyCollection {
60 ///     fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
61 ///         let mut c = MyCollection::new();
62 ///
63 ///         for i in iter {
64 ///             c.add(i);
65 ///         }
66 ///
67 ///         c
68 ///     }
69 /// }
70 ///
71 /// // Now we can make a new iterator...
72 /// let iter = (0..5).into_iter();
73 ///
74 /// // ... and make a MyCollection out of it
75 /// let c = MyCollection::from_iter(iter);
76 ///
77 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
78 ///
79 /// // collect works too!
80 ///
81 /// let iter = (0..5).into_iter();
82 /// let c: MyCollection = iter.collect();
83 ///
84 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
85 /// ```
86 #[stable(feature = "rust1", since = "1.0.0")]
87 #[rustc_on_unimplemented(
88     message = "a value of type `{Self}` cannot be built from an iterator \
89                over elements of type `{A}`",
90     label = "value of type `{Self}` cannot be built from `std::iter::Iterator<Item={A}>`"
91 )]
92 pub trait FromIterator<A>: Sized {
93     /// Creates a value from an iterator.
94     ///
95     /// See the [module-level documentation] for more.
96     ///
97     /// [module-level documentation]: index.html
98     ///
99     /// # Examples
100     ///
101     /// Basic usage:
102     ///
103     /// ```
104     /// use std::iter::FromIterator;
105     ///
106     /// let five_fives = std::iter::repeat(5).take(5);
107     ///
108     /// let v = Vec::from_iter(five_fives);
109     ///
110     /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
111     /// ```
112     #[stable(feature = "rust1", since = "1.0.0")]
113     fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self;
114 }
115
116 /// Conversion into an [`Iterator`].
117 ///
118 /// By implementing `IntoIterator` for a type, you define how it will be
119 /// converted to an iterator. This is common for types which describe a
120 /// collection of some kind.
121 ///
122 /// One benefit of implementing `IntoIterator` is that your type will [work
123 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
124 ///
125 /// See also: [`FromIterator`].
126 ///
127 /// # Examples
128 ///
129 /// Basic usage:
130 ///
131 /// ```
132 /// let v = vec![1, 2, 3];
133 /// let mut iter = v.into_iter();
134 ///
135 /// assert_eq!(Some(1), iter.next());
136 /// assert_eq!(Some(2), iter.next());
137 /// assert_eq!(Some(3), iter.next());
138 /// assert_eq!(None, iter.next());
139 /// ```
140 /// Implementing `IntoIterator` for your type:
141 ///
142 /// ```
143 /// // A sample collection, that's just a wrapper over Vec<T>
144 /// #[derive(Debug)]
145 /// struct MyCollection(Vec<i32>);
146 ///
147 /// // Let's give it some methods so we can create one and add things
148 /// // to it.
149 /// impl MyCollection {
150 ///     fn new() -> MyCollection {
151 ///         MyCollection(Vec::new())
152 ///     }
153 ///
154 ///     fn add(&mut self, elem: i32) {
155 ///         self.0.push(elem);
156 ///     }
157 /// }
158 ///
159 /// // and we'll implement IntoIterator
160 /// impl IntoIterator for MyCollection {
161 ///     type Item = i32;
162 ///     type IntoIter = std::vec::IntoIter<Self::Item>;
163 ///
164 ///     fn into_iter(self) -> Self::IntoIter {
165 ///         self.0.into_iter()
166 ///     }
167 /// }
168 ///
169 /// // Now we can make a new collection...
170 /// let mut c = MyCollection::new();
171 ///
172 /// // ... add some stuff to it ...
173 /// c.add(0);
174 /// c.add(1);
175 /// c.add(2);
176 ///
177 /// // ... and then turn it into an Iterator:
178 /// for (i, n) in c.into_iter().enumerate() {
179 ///     assert_eq!(i as i32, n);
180 /// }
181 /// ```
182 ///
183 /// It is common to use `IntoIterator` as a trait bound. This allows
184 /// the input collection type to change, so long as it is still an
185 /// iterator. Additional bounds can be specified by restricting on
186 /// `Item`:
187 ///
188 /// ```rust
189 /// fn collect_as_strings<T>(collection: T) -> Vec<String>
190 /// where
191 ///     T: IntoIterator,
192 ///     T::Item: std::fmt::Debug,
193 /// {
194 ///     collection
195 ///         .into_iter()
196 ///         .map(|item| format!("{:?}", item))
197 ///         .collect()
198 /// }
199 /// ```
200 #[rustc_diagnostic_item = "IntoIterator"]
201 #[stable(feature = "rust1", since = "1.0.0")]
202 pub trait IntoIterator {
203     /// The type of the elements being iterated over.
204     #[stable(feature = "rust1", since = "1.0.0")]
205     type Item;
206
207     /// Which kind of iterator are we turning this into?
208     #[stable(feature = "rust1", since = "1.0.0")]
209     type IntoIter: Iterator<Item = Self::Item>;
210
211     /// Creates an iterator from a value.
212     ///
213     /// See the [module-level documentation] for more.
214     ///
215     /// [module-level documentation]: index.html
216     ///
217     /// # Examples
218     ///
219     /// Basic usage:
220     ///
221     /// ```
222     /// let v = vec![1, 2, 3];
223     /// let mut iter = v.into_iter();
224     ///
225     /// assert_eq!(Some(1), iter.next());
226     /// assert_eq!(Some(2), iter.next());
227     /// assert_eq!(Some(3), iter.next());
228     /// assert_eq!(None, iter.next());
229     /// ```
230     #[lang = "into_iter"]
231     #[stable(feature = "rust1", since = "1.0.0")]
232     fn into_iter(self) -> Self::IntoIter;
233 }
234
235 #[stable(feature = "rust1", since = "1.0.0")]
236 impl<I: Iterator> IntoIterator for I {
237     type Item = I::Item;
238     type IntoIter = I;
239
240     fn into_iter(self) -> I {
241         self
242     }
243 }
244
245 /// Extend a collection with the contents of an iterator.
246 ///
247 /// Iterators produce a series of values, and collections can also be thought
248 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
249 /// to extend a collection by including the contents of that iterator. When
250 /// extending a collection with an already existing key, that entry is updated
251 /// or, in the case of collections that permit multiple entries with equal
252 /// keys, that entry is inserted.
253 ///
254 /// # Examples
255 ///
256 /// Basic usage:
257 ///
258 /// ```
259 /// // You can extend a String with some chars:
260 /// let mut message = String::from("The first three letters are: ");
261 ///
262 /// message.extend(&['a', 'b', 'c']);
263 ///
264 /// assert_eq!("abc", &message[29..32]);
265 /// ```
266 ///
267 /// Implementing `Extend`:
268 ///
269 /// ```
270 /// // A sample collection, that's just a wrapper over Vec<T>
271 /// #[derive(Debug)]
272 /// struct MyCollection(Vec<i32>);
273 ///
274 /// // Let's give it some methods so we can create one and add things
275 /// // to it.
276 /// impl MyCollection {
277 ///     fn new() -> MyCollection {
278 ///         MyCollection(Vec::new())
279 ///     }
280 ///
281 ///     fn add(&mut self, elem: i32) {
282 ///         self.0.push(elem);
283 ///     }
284 /// }
285 ///
286 /// // since MyCollection has a list of i32s, we implement Extend for i32
287 /// impl Extend<i32> for MyCollection {
288 ///
289 ///     // This is a bit simpler with the concrete type signature: we can call
290 ///     // extend on anything which can be turned into an Iterator which gives
291 ///     // us i32s. Because we need i32s to put into MyCollection.
292 ///     fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
293 ///
294 ///         // The implementation is very straightforward: loop through the
295 ///         // iterator, and add() each element to ourselves.
296 ///         for elem in iter {
297 ///             self.add(elem);
298 ///         }
299 ///     }
300 /// }
301 ///
302 /// let mut c = MyCollection::new();
303 ///
304 /// c.add(5);
305 /// c.add(6);
306 /// c.add(7);
307 ///
308 /// // let's extend our collection with three more numbers
309 /// c.extend(vec![1, 2, 3]);
310 ///
311 /// // we've added these elements onto the end
312 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
313 /// ```
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub trait Extend<A> {
316     /// Extends a collection with the contents of an iterator.
317     ///
318     /// As this is the only required method for this trait, the [trait-level] docs
319     /// contain more details.
320     ///
321     /// [trait-level]: Extend
322     ///
323     /// # Examples
324     ///
325     /// Basic usage:
326     ///
327     /// ```
328     /// // You can extend a String with some chars:
329     /// let mut message = String::from("abc");
330     ///
331     /// message.extend(['d', 'e', 'f'].iter());
332     ///
333     /// assert_eq!("abcdef", &message);
334     /// ```
335     #[stable(feature = "rust1", since = "1.0.0")]
336     fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T);
337
338     /// Extends a collection with exactly one element.
339     #[unstable(feature = "extend_one", issue = "72631")]
340     fn extend_one(&mut self, item: A) {
341         self.extend(Some(item));
342     }
343
344     /// Reserves capacity in a collection for the given number of additional elements.
345     ///
346     /// The default implementation does nothing.
347     #[unstable(feature = "extend_one", issue = "72631")]
348     fn extend_reserve(&mut self, additional: usize) {
349         let _ = additional;
350     }
351 }
352
353 #[stable(feature = "extend_for_unit", since = "1.28.0")]
354 impl Extend<()> for () {
355     fn extend<T: IntoIterator<Item = ()>>(&mut self, iter: T) {
356         iter.into_iter().for_each(drop)
357     }
358     fn extend_one(&mut self, _item: ()) {}
359 }