]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/traits/collect.rs
Rollup merge of #66060 - traxys:test_65401, r=michaelwoerister
[rust.git] / src / libcore / 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 collection of type `{Self}` cannot be built from an iterator \
95              over elements of type `{A}`",
96     label="a collection 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     #[stable(feature = "rust1", since = "1.0.0")]
239     fn into_iter(self) -> Self::IntoIter;
240 }
241
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl<I: Iterator> IntoIterator for I {
244     type Item = I::Item;
245     type IntoIter = I;
246
247     fn into_iter(self) -> I {
248         self
249     }
250 }
251
252 /// Extend a collection with the contents of an iterator.
253 ///
254 /// Iterators produce a series of values, and collections can also be thought
255 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
256 /// to extend a collection by including the contents of that iterator. When
257 /// extending a collection with an already existing key, that entry is updated
258 /// or, in the case of collections that permit multiple entries with equal
259 /// keys, that entry is inserted.
260 ///
261 /// # Examples
262 ///
263 /// Basic usage:
264 ///
265 /// ```
266 /// // You can extend a String with some chars:
267 /// let mut message = String::from("The first three letters are: ");
268 ///
269 /// message.extend(&['a', 'b', 'c']);
270 ///
271 /// assert_eq!("abc", &message[29..32]);
272 /// ```
273 ///
274 /// Implementing `Extend`:
275 ///
276 /// ```
277 /// // A sample collection, that's just a wrapper over Vec<T>
278 /// #[derive(Debug)]
279 /// struct MyCollection(Vec<i32>);
280 ///
281 /// // Let's give it some methods so we can create one and add things
282 /// // to it.
283 /// impl MyCollection {
284 ///     fn new() -> MyCollection {
285 ///         MyCollection(Vec::new())
286 ///     }
287 ///
288 ///     fn add(&mut self, elem: i32) {
289 ///         self.0.push(elem);
290 ///     }
291 /// }
292 ///
293 /// // since MyCollection has a list of i32s, we implement Extend for i32
294 /// impl Extend<i32> for MyCollection {
295 ///
296 ///     // This is a bit simpler with the concrete type signature: we can call
297 ///     // extend on anything which can be turned into an Iterator which gives
298 ///     // us i32s. Because we need i32s to put into MyCollection.
299 ///     fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
300 ///
301 ///         // The implementation is very straightforward: loop through the
302 ///         // iterator, and add() each element to ourselves.
303 ///         for elem in iter {
304 ///             self.add(elem);
305 ///         }
306 ///     }
307 /// }
308 ///
309 /// let mut c = MyCollection::new();
310 ///
311 /// c.add(5);
312 /// c.add(6);
313 /// c.add(7);
314 ///
315 /// // let's extend our collection with three more numbers
316 /// c.extend(vec![1, 2, 3]);
317 ///
318 /// // we've added these elements onto the end
319 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
320 /// ```
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub trait Extend<A> {
323     /// Extends a collection with the contents of an iterator.
324     ///
325     /// As this is the only method for this trait, the [trait-level] docs
326     /// contain more details.
327     ///
328     /// [trait-level]: trait.Extend.html
329     ///
330     /// # Examples
331     ///
332     /// Basic usage:
333     ///
334     /// ```
335     /// // You can extend a String with some chars:
336     /// let mut message = String::from("abc");
337     ///
338     /// message.extend(['d', 'e', 'f'].iter());
339     ///
340     /// assert_eq!("abcdef", &message);
341     /// ```
342     #[stable(feature = "rust1", since = "1.0.0")]
343     fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T);
344 }
345
346 #[stable(feature = "extend_for_unit", since = "1.28.0")]
347 impl Extend<()> for () {
348     fn extend<T: IntoIterator<Item = ()>>(&mut self, iter: T) {
349         iter.into_iter().for_each(drop)
350     }
351 }