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 /// [`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.
11 /// See also: [`IntoIterator`].
18 /// use std::iter::FromIterator;
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 /// Implementing `FromIterator` for your type:
40 /// use std::iter::FromIterator;
42 /// // A sample collection, that's just a wrapper over Vec<T>
44 /// struct MyCollection(Vec<i32>);
46 /// // Let's give it some methods so we can create one and add things
48 /// impl MyCollection {
49 /// fn new() -> MyCollection {
50 /// MyCollection(Vec::new())
53 /// fn add(&mut self, elem: i32) {
54 /// self.0.push(elem);
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();
71 /// // Now we can make a new iterator...
72 /// let iter = (0..5).into_iter();
74 /// // ... and make a MyCollection out of it
75 /// let c = MyCollection::from_iter(iter);
77 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
79 /// // collect works too!
81 /// let iter = (0..5).into_iter();
82 /// let c: MyCollection = iter.collect();
84 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
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}>`"
92 pub trait FromIterator<A>: Sized {
93 /// Creates a value from an iterator.
95 /// See the [module-level documentation] for more.
97 /// [module-level documentation]: index.html
104 /// use std::iter::FromIterator;
106 /// let five_fives = std::iter::repeat(5).take(5);
108 /// let v = Vec::from_iter(five_fives);
110 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
112 #[stable(feature = "rust1", since = "1.0.0")]
113 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self;
116 /// Conversion into an [`Iterator`].
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.
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).
125 /// See also: [`FromIterator`].
132 /// let v = vec![1, 2, 3];
133 /// let mut iter = v.into_iter();
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());
140 /// Implementing `IntoIterator` for your type:
143 /// // A sample collection, that's just a wrapper over Vec<T>
145 /// struct MyCollection(Vec<i32>);
147 /// // Let's give it some methods so we can create one and add things
149 /// impl MyCollection {
150 /// fn new() -> MyCollection {
151 /// MyCollection(Vec::new())
154 /// fn add(&mut self, elem: i32) {
155 /// self.0.push(elem);
159 /// // and we'll implement IntoIterator
160 /// impl IntoIterator for MyCollection {
162 /// type IntoIter = std::vec::IntoIter<Self::Item>;
164 /// fn into_iter(self) -> Self::IntoIter {
165 /// self.0.into_iter()
169 /// // Now we can make a new collection...
170 /// let mut c = MyCollection::new();
172 /// // ... add some stuff to it ...
177 /// // ... and then turn it into an Iterator:
178 /// for (i, n) in c.into_iter().enumerate() {
179 /// assert_eq!(i as i32, n);
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
189 /// fn collect_as_strings<T>(collection: T) -> Vec<String>
192 /// T::Item: std::fmt::Debug,
196 /// .map(|item| format!("{:?}", item))
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")]
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>;
211 /// Creates an iterator from a value.
213 /// See the [module-level documentation] for more.
215 /// [module-level documentation]: index.html
222 /// let v = vec![1, 2, 3];
223 /// let mut iter = v.into_iter();
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());
230 #[lang = "into_iter"]
231 #[stable(feature = "rust1", since = "1.0.0")]
232 fn into_iter(self) -> Self::IntoIter;
235 #[stable(feature = "rust1", since = "1.0.0")]
236 impl<I: Iterator> IntoIterator for I {
240 fn into_iter(self) -> I {
245 /// Extend a collection with the contents of an iterator.
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.
259 /// // You can extend a String with some chars:
260 /// let mut message = String::from("The first three letters are: ");
262 /// message.extend(&['a', 'b', 'c']);
264 /// assert_eq!("abc", &message[29..32]);
267 /// Implementing `Extend`:
270 /// // A sample collection, that's just a wrapper over Vec<T>
272 /// struct MyCollection(Vec<i32>);
274 /// // Let's give it some methods so we can create one and add things
276 /// impl MyCollection {
277 /// fn new() -> MyCollection {
278 /// MyCollection(Vec::new())
281 /// fn add(&mut self, elem: i32) {
282 /// self.0.push(elem);
286 /// // since MyCollection has a list of i32s, we implement Extend for i32
287 /// impl Extend<i32> for MyCollection {
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) {
294 /// // The implementation is very straightforward: loop through the
295 /// // iterator, and add() each element to ourselves.
296 /// for elem in iter {
302 /// let mut c = MyCollection::new();
308 /// // let's extend our collection with three more numbers
309 /// c.extend(vec![1, 2, 3]);
311 /// // we've added these elements onto the end
312 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub trait Extend<A> {
316 /// Extends a collection with the contents of an iterator.
318 /// As this is the only required method for this trait, the [trait-level] docs
319 /// contain more details.
321 /// [trait-level]: Extend
328 /// // You can extend a String with some chars:
329 /// let mut message = String::from("abc");
331 /// message.extend(['d', 'e', 'f'].iter());
333 /// assert_eq!("abcdef", &message);
335 #[stable(feature = "rust1", since = "1.0.0")]
336 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T);
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));
344 /// Reserves capacity in a collection for the given number of additional elements.
346 /// The default implementation does nothing.
347 #[unstable(feature = "extend_one", issue = "72631")]
348 fn extend_reserve(&mut self, additional: usize) {
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)
358 fn extend_one(&mut self, _item: ()) {}