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`'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.
11 /// [`from_iter`]: #tymethod.from_iter
12 /// [`Iterator`]: trait.Iterator.html
13 /// [`collect`]: trait.Iterator.html#method.collect
15 /// See also: [`IntoIterator`].
17 /// [`IntoIterator`]: trait.IntoIterator.html
24 /// use std::iter::FromIterator;
26 /// let five_fives = std::iter::repeat(5).take(5);
28 /// let v = Vec::from_iter(five_fives);
30 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
33 /// Using [`collect`] to implicitly use `FromIterator`:
36 /// let five_fives = std::iter::repeat(5).take(5);
38 /// let v: Vec<i32> = five_fives.collect();
40 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
43 /// Implementing `FromIterator` for your type:
46 /// use std::iter::FromIterator;
48 /// // A sample collection, that's just a wrapper over Vec<T>
50 /// struct MyCollection(Vec<i32>);
52 /// // Let's give it some methods so we can create one and add things
54 /// impl MyCollection {
55 /// fn new() -> MyCollection {
56 /// MyCollection(Vec::new())
59 /// fn add(&mut self, elem: i32) {
60 /// self.0.push(elem);
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();
77 /// // Now we can make a new iterator...
78 /// let iter = (0..5).into_iter();
80 /// // ... and make a MyCollection out of it
81 /// let c = MyCollection::from_iter(iter);
83 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
85 /// // collect works too!
87 /// let iter = (0..5).into_iter();
88 /// let c: MyCollection = iter.collect();
90 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
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}>`",
98 pub trait FromIterator<A>: Sized {
99 /// Creates a value from an iterator.
101 /// See the [module-level documentation] for more.
103 /// [module-level documentation]: index.html
110 /// use std::iter::FromIterator;
112 /// let five_fives = std::iter::repeat(5).take(5);
114 /// let v = Vec::from_iter(five_fives);
116 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
118 #[stable(feature = "rust1", since = "1.0.0")]
119 fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> Self;
122 /// Conversion into an `Iterator`.
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.
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).
131 /// See also: [`FromIterator`].
133 /// [`FromIterator`]: trait.FromIterator.html
140 /// let v = vec![1, 2, 3];
141 /// let mut iter = v.into_iter();
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());
148 /// Implementing `IntoIterator` for your type:
151 /// // A sample collection, that's just a wrapper over Vec<T>
153 /// struct MyCollection(Vec<i32>);
155 /// // Let's give it some methods so we can create one and add things
157 /// impl MyCollection {
158 /// fn new() -> MyCollection {
159 /// MyCollection(Vec::new())
162 /// fn add(&mut self, elem: i32) {
163 /// self.0.push(elem);
167 /// // and we'll implement IntoIterator
168 /// impl IntoIterator for MyCollection {
170 /// type IntoIter = std::vec::IntoIter<Self::Item>;
172 /// fn into_iter(self) -> Self::IntoIter {
173 /// self.0.into_iter()
177 /// // Now we can make a new collection...
178 /// let mut c = MyCollection::new();
180 /// // ... add some stuff to it ...
185 /// // ... and then turn it into an Iterator:
186 /// for (i, n) in c.into_iter().enumerate() {
187 /// assert_eq!(i as i32, n);
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
197 /// fn collect_as_strings<T>(collection: T) -> Vec<String>
200 /// T::Item: std::fmt::Debug,
204 /// .map(|item| format!("{:?}", item))
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")]
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>;
219 /// Creates an iterator from a value.
221 /// See the [module-level documentation] for more.
223 /// [module-level documentation]: index.html
230 /// let v = vec![1, 2, 3];
231 /// let mut iter = v.into_iter();
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());
238 #[stable(feature = "rust1", since = "1.0.0")]
239 fn into_iter(self) -> Self::IntoIter;
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl<I: Iterator> IntoIterator for I {
247 fn into_iter(self) -> I {
252 /// Extend a collection with the contents of an iterator.
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.
266 /// // You can extend a String with some chars:
267 /// let mut message = String::from("The first three letters are: ");
269 /// message.extend(&['a', 'b', 'c']);
271 /// assert_eq!("abc", &message[29..32]);
274 /// Implementing `Extend`:
277 /// // A sample collection, that's just a wrapper over Vec<T>
279 /// struct MyCollection(Vec<i32>);
281 /// // Let's give it some methods so we can create one and add things
283 /// impl MyCollection {
284 /// fn new() -> MyCollection {
285 /// MyCollection(Vec::new())
288 /// fn add(&mut self, elem: i32) {
289 /// self.0.push(elem);
293 /// // since MyCollection has a list of i32s, we implement Extend for i32
294 /// impl Extend<i32> for MyCollection {
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) {
301 /// // The implementation is very straightforward: loop through the
302 /// // iterator, and add() each element to ourselves.
303 /// for elem in iter {
309 /// let mut c = MyCollection::new();
315 /// // let's extend our collection with three more numbers
316 /// c.extend(vec![1, 2, 3]);
318 /// // we've added these elements onto the end
319 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub trait Extend<A> {
323 /// Extends a collection with the contents of an iterator.
325 /// As this is the only method for this trait, the [trait-level] docs
326 /// contain more details.
328 /// [trait-level]: trait.Extend.html
335 /// // You can extend a String with some chars:
336 /// let mut message = String::from("abc");
338 /// message.extend(['d', 'e', 'f'].iter());
340 /// assert_eq!("abcdef", &message);
342 #[stable(feature = "rust1", since = "1.0.0")]
343 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T);
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)