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