]>
git.proxmox.com Git - rustc.git/blob - library/core/src/iter/traits/collect.rs
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]: crate::iter
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](crate::iter#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 #[cfg_attr(not(bootstrap), rustc_skip_array_during_method_dispatch)]
202 #[stable(feature = "rust1", since = "1.0.0")]
203 pub trait IntoIterator
{
204 /// The type of the elements being iterated over.
205 #[stable(feature = "rust1", since = "1.0.0")]
208 /// Which kind of iterator are we turning this into?
209 #[stable(feature = "rust1", since = "1.0.0")]
210 type IntoIter
: Iterator
<Item
= Self::Item
>;
212 /// Creates an iterator from a value.
214 /// See the [module-level documentation] for more.
216 /// [module-level documentation]: crate::iter
223 /// let v = vec![1, 2, 3];
224 /// let mut iter = v.into_iter();
226 /// assert_eq!(Some(1), iter.next());
227 /// assert_eq!(Some(2), iter.next());
228 /// assert_eq!(Some(3), iter.next());
229 /// assert_eq!(None, iter.next());
231 #[lang = "into_iter"]
232 #[stable(feature = "rust1", since = "1.0.0")]
233 fn into_iter(self) -> Self::IntoIter
;
236 #[stable(feature = "rust1", since = "1.0.0")]
237 impl<I
: Iterator
> IntoIterator
for I
{
241 fn into_iter(self) -> I
{
246 /// Extend a collection with the contents of an iterator.
248 /// Iterators produce a series of values, and collections can also be thought
249 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
250 /// to extend a collection by including the contents of that iterator. When
251 /// extending a collection with an already existing key, that entry is updated
252 /// or, in the case of collections that permit multiple entries with equal
253 /// keys, that entry is inserted.
260 /// // You can extend a String with some chars:
261 /// let mut message = String::from("The first three letters are: ");
263 /// message.extend(&['a', 'b', 'c']);
265 /// assert_eq!("abc", &message[29..32]);
268 /// Implementing `Extend`:
271 /// // A sample collection, that's just a wrapper over Vec<T>
273 /// struct MyCollection(Vec<i32>);
275 /// // Let's give it some methods so we can create one and add things
277 /// impl MyCollection {
278 /// fn new() -> MyCollection {
279 /// MyCollection(Vec::new())
282 /// fn add(&mut self, elem: i32) {
283 /// self.0.push(elem);
287 /// // since MyCollection has a list of i32s, we implement Extend for i32
288 /// impl Extend<i32> for MyCollection {
290 /// // This is a bit simpler with the concrete type signature: we can call
291 /// // extend on anything which can be turned into an Iterator which gives
292 /// // us i32s. Because we need i32s to put into MyCollection.
293 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
295 /// // The implementation is very straightforward: loop through the
296 /// // iterator, and add() each element to ourselves.
297 /// for elem in iter {
303 /// let mut c = MyCollection::new();
309 /// // let's extend our collection with three more numbers
310 /// c.extend(vec![1, 2, 3]);
312 /// // we've added these elements onto the end
313 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub trait Extend
<A
> {
317 /// Extends a collection with the contents of an iterator.
319 /// As this is the only required method for this trait, the [trait-level] docs
320 /// contain more details.
322 /// [trait-level]: Extend
329 /// // You can extend a String with some chars:
330 /// let mut message = String::from("abc");
332 /// message.extend(['d', 'e', 'f'].iter());
334 /// assert_eq!("abcdef", &message);
336 #[stable(feature = "rust1", since = "1.0.0")]
337 fn extend
<T
: IntoIterator
<Item
= A
>>(&mut self, iter
: T
);
339 /// Extends a collection with exactly one element.
340 #[unstable(feature = "extend_one", issue = "72631")]
341 fn extend_one(&mut self, item
: A
) {
342 self.extend(Some(item
));
345 /// Reserves capacity in a collection for the given number of additional elements.
347 /// The default implementation does nothing.
348 #[unstable(feature = "extend_one", issue = "72631")]
349 fn extend_reserve(&mut self, additional
: usize) {
354 #[stable(feature = "extend_for_unit", since = "1.28.0")]
355 impl Extend
<()> for () {
356 fn extend
<T
: IntoIterator
<Item
= ()>>(&mut self, iter
: T
) {
357 iter
.into_iter().for_each(drop
)
359 fn extend_one(&mut self, _item
: ()) {}