bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 5쪽
e the [module-level documentation](./core-iter) for more.
#### Signature
```rust theme={null}
fn from_iter,
+TypeEqual,
+Destruct,
+Destruct,
>(
iter: I,
) -> T
```
#### Examples
```rust theme={null}
let iter = (0..5_u32).into_iter();
let v = FromIterator::from_iter(iter);
assert_eq!(v, array![0, 1, 2, 3, 4]);
```
# core::iter::traits::collect::IntoIterator
Source: https://docs.starknet.io/build/corelib/core-iter-traits-collect-IntoIterator
Conversion into an [`Iterator`](./core-iter-traits-iterator-Iterator).
By implementing `IntoIterator` for a type, you define how it will be
converted to an iterator. This is common for types which describe a
collection of some kind.
One benefit of implementing `IntoIterator` is that your type will work
with Cairo's `for` loop syntax.
See also: [`FromIterator`](./core-iter-traits-collect-FromIterator).
## Signature
```rust theme={null}
pub trait IntoIterator
```
## Examples
Basic usage:
```rust theme={null}
let mut iter = array![1, 2, 3].into_iter();
assert!(Some(1) == iter.next());
assert!(Some(2) == iter.next());
assert!(Some(3) == iter.next());
assert!(None == iter.next());
```
Implementing `IntoIterator` for your type:
```rust theme={null}
// A sample collection, that's just a wrapper over `Array`
#[derive(Drop, Debug)]
struct MyCollection {
arr: Array
}
// Let's give it some methods so we can create one and add things
// to it.
#[generate_trait]
impl MyCollectionImpl of MyCollectionTrait {
fn new() -> MyCollection {
MyCollection {
arr: ArrayTrait::new()
}
}
fn add(ref self: MyCollection, elem: u32) {
self.arr.append(elem);
}
}
// and we'll implement `IntoIterator`
impl MyCollectionIntoIterator of IntoIterator {
type IntoIter = core::array::ArrayIter;
fn into_iter(self: MyCollection) -> Self::IntoIter {
self.arr.into_iter()
}
}
// Now we can make a new collection...
let mut c = MyCollectionTrait::new();
// ... add some stuff to it ...
c.add(0);
c.add(1);
c.add(2);
// ... and then turn it into an `Iterator`:
let mut n = 0;
for i in c {
assert!(i == n);
n += 1;
};
```
## Trait functions
### into\_iter
Creates an iterator from a value.
See the [module-level documentation](./core-iter) for more.
#### Signature
```rust theme={null}
fn into_iter(self: T) -> IntoIteratorIntoIter
```
#### Examples
```rust theme={null}
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(Some(1), iter.next());
assert_eq!(Some(2), iter.next());
assert_eq!(Some(3), iter.next());
assert_eq!(None, iter.next());
```
## Trait types
### IntoIter
The iterator type that will be created.
#### Signature
```rust theme={null}
type IntoIter;
```
# core::iter::traits::iterator::Iterator
Source: https://docs.starknet.io/build/corelib/core-iter-traits-iterator-Iterator
A trait for dealing with iterators.
This is the main iterator trait. For more about the concept of iterators
generally, please see the [module-level documentation](./core-iter). In particular, you
may want to know how to [implement `Iterator`](./core-iter).
## Signature
```rust theme={null}
pub trait Iterator
```
## Trait functions
### next
Advances the iterator and returns the next value.
Returns [`None`](./core-option#none) when iteration is finished. Individual iterator
implementations may choose to resume iteration, and so calling `next()`
again may or may not eventually start returning [`Some(Item)`](./core-option#some) again at some
point.
#### Signature
```rust theme={null}
fn next(ref self: T) -> OptionItem>
```
#### Examples
```rust theme={null}
let mut iter = [1, 2, 3].span().into_iter();
// A call to next() returns the next value...
assert_eq!(Some(@1), iter.next());
assert_eq!(Some(@2), iter.next());
assert_eq!(Some(@3), iter.next());
// ... and then None once it's over.
assert_eq!(None, iter.next());
// More calls may or may not return `None`. Here, they always will.
assert_eq!(None, iter.next());
assert_eq!(None, iter.next());
```
### count
Consumes the iterator, counting the number of iterations and returning it.
This method will call `next` repeatedly until [`None`](./core-option#none) is encountered,
returning the number of times it saw [`Some`](./core-option#some). Note that `next` has to be
called at least once even if the iterator does not have any elements.
#### Overflow Behavior
The method does no guarding against overflows, so counting elements of
an iterator with more than [`Bounded::::MAX`](./core-num-traits-bounded-Bounded) elements either produces the
wrong result or panics.
#### Panics
This function might panic if the iterator has more than [`Bounded::::MAX`](./core-num-traits-bounded-Bounded)
elements.
#### Examples
```rust theme={null}
let mut a = array![1, 2, 3].into_iter();
assert_eq!(a.count(), 3);
let mut a = array![1, 2, 3, 4, 5].into_iter();
assert_eq!(a.count(), 5);
```
#### Signature
```rust theme={null}
fn count, +Destruct>(self: T) -> u32
```
### last
Consumes the iterator, returning the last element.
This method will evaluate the iterator until it returns [`None`](./core-option#none). While
doing so, it keeps track of the current element. After [`None`](./core-option#none) is
returned, `last()` will then return the last element it saw.
#### Signature
```rust theme={null}
fn last, +Destruct>(self: T) -> OptionItem>
```
#### Examples
```rust theme={null}
let mut a = array![1, 2, 3].into_iter();
assert_eq!(a.last(), Option::Some(3));
let mut a = array![].into_iter();
assert_eq!(a.last(), Option::None);
```
### advance\_by
Advances the iterator by `n` elements.
This method will eagerly skip `n` elements by calling `next` up to `n`
times until [`None`](./core-option#none) is encountered.
`advance_by(n)` will return `Ok(())` if the iterator successfully advances by
`n` elements, or a `Err(NonZero)` with value `k` if [`None`](./core-option#none) is encountered,
where `k` is remaining number of steps that could not be advanced because the iterator ran
out.
If `self` is empty and `n` is non-zero, then this returns `Err(n)`.
Otherwise, `k` is always less than `n`.
#### Signature
```rust theme={null}
fn advance_by, +Destruct>(
ref self: T, n: u32,
) -> Result>
```
#### Examples
```rust theme={null}
let mut iter = array![1_u8, 2, 3, 4].into_iter();
assert_eq!(iter.advance_by(2), Ok(()));
assert_eq!(iter.next(), Some(3));
assert_eq!(iter.advance_by(0), Ok(()));
assert_eq!(iter.advance_by(100), Err(99));
```
### nth
Returns the `n`th element of the iterator.
Like most indexing operations, the count starts from zero, so `nth(0)`
returns the first value, `nth(1)` the second, and so on.
Note that all preceding elements, as well as the returned element, will be
consumed from the iterator. That means that the preceding elements will be
discarded, and also that calling `nth(0)` multiple times on the same iterator
will return different elements.
`nth()` will return [`None`](./core-option#none) if `n` is greater than or equal to the length of the
iterator.
#### Signature
```rust theme={null}
fn nth, +Destruct>(ref self: T, n: u32) -> OptionItem>
```
#### Examples
Basic usage:
```rust theme={null}
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(iter.nth(1), Some(2));
```
Calling `nth()` multiple times doesn't rewind the iterator:
```rust theme={null}
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(iter.nth(1), Some(2));
assert_eq!(iter.nth(1), None);
```
Returning `None` if there are less than `n + 1` elements:
```rust theme={null}
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(iter.nth(10), None);
```
### map
Takes a closure and creates an iterator which calls that closure on each
element.
`map()` transforms one iterator into another, by means of its argument:
something that implements `FnOnce`. It produces a new iterator which
calls this closure on each element of the original iterator.
If you are good at thinking in types, you can think of `map()` like this:
If you have an iterator that gives you elements of some type `A`, and
you want an iterator of some other type `B`, you can use `map()`,
passing a closure that takes an `A` and returns a `B`.
`map()` is conceptually similar to a `for` loop. However, as `map()` is
lazy, it is best used when you're already working with other iterators.
If you're doing some sort of looping for a side effect, it's considered
more idiomatic to use `for` than `map()`.
#### Signature
```rust theme={null}
fn map[Output: B], +Drop, +Drop>(
self: T, f: F,
) -> Map
```
#### Examples
Basic usage:
```rust theme={null}
let mut iter = array![1, 2, 3].into_iter().map(|x| 2 * x);
assert!(iter.next() == Some(2));
assert!(iter.next() == Some(4));
assert!(iter.next() == Some(6));
assert!(iter.next() == None);
```
If you're doing some sort of side effect, prefer `for` to `map()`:
```rust theme={null}
// don't do this:
let _ = (0..5_usize).into_iter().map(|x| println!("{x}"));
// it won't even execute, as it is lazy. Cairo will warn you about this if not specifically
ignored, as is done here.
// Instead, use for:
for x in 0..5_usize {
println!("{x}");
}
```
### enumerate
Creates an iterator which gives the current iteration count as well as
the next value.
The iterator returned yields pairs `(i, val)`, where `i` is the
current index of iteration and `val` is the value returned by the
iterator.
`enumerate()` keeps its count as a [`usize`](./core-usize).
#### Overflow Behavior
The method does no guarding against overflows, so enumerating more than
`Bounded::::MAX` elements will always panic.
#### Panics
Will panic if the to-be-returned index overflows a `usize`.
#### Examples
```rust theme={null}
let mut iter = array!['a', 'b', 'c'].into_iter().enumerate();
assert_eq!(iter.next(), Some((0, 'a')));
assert_eq!(iter.next(), Some((1, 'b')));
assert_eq!(iter.next(), Some((2, 'c')));
assert_eq!(iter.next(), None);
```
#### Signature
```rust theme={null}
fn enumerate(self: T) -> Enumerate
```
### fold
Folds every element into an accumulator by applying an operation,
returning the final result.
`fold()` takes two arguments: an initial value, and a closure with two
arguments: an 'accumulator', and an element. The closure returns the value that
the accumulator should have for the next iteration.
The initial value is the value the accumulator will have on the first
call.
After applying this closure to every element of the iterator, `fold()`
returns the accumulator.
Folding is useful whenever you have a collection of something, and want
to produce a single value from it.
Note: `fold()`, and similar methods that traverse the entire iterator,
might not terminate for infinite iterators, even on traits for which a
result is determinable in finite time.
Note: `fold()` combines elements in a left-associative fashion. For associative
operators like `+`, the order the elements are combined in is not important, but for
non-associative operators like `-` the order will affect the final result.
#### Note to Implementers
Several of the other (forward) methods have default implementations in
terms of this one, so try to implement this explicitly if it can
do something better than the default `for` loop implementation.
In particular, try to have this call `fold()` on the internal parts
from which this iterator is composed.
#### Examples
Basic usage:
```rust theme={null}
let mut iter = array![1, 2, 3].into_iter();
// the sum of all of the elements of the array
let sum = iter.fold(0, |acc, x| acc + x);
assert_eq!(sum, 6);
```
Let's walk through each step of the iteration here:
| element | acc | x | result |
| - | - | - | - |
| | 0 | | |
| 1 | 0 | 1 | 1 |
| 2 | 1 | 2 | 3 |
| 3 | 3 | 3 | 6 |
And so, our final result, `6`.
It's common for people who haven't used iterators a lot to
use a `for` loop with a list of things to build up a result. Those
can be turned into `fold()`s:
```rust theme={null}
let mut numbers = array![1, 2, 3, 4, 5].span();
let mut result = 0;
// for loop:
for i in numbers{
result = result + (*i);
};
// fold:
let mut numbers_iter = numbers.into_iter();
let result2 = numbers_iter.fold(0, |acc, x| acc + (*x));
// they're the same
assert_eq!(result, result2);
```
#### Signature
```rust theme={null}
fn fold[Output: B],
+Destruct,
+Destruct,
+Destruct,
>(
ref self: T, init: B, f: F,
) -> B
```
### any
Tests if any element of the iterator matches a predicate.
`any()` takes a closure that returns `true` or `false`. It applies this closure to each
element of the iterator, and if any of them return `true`, then so does `any()`. If they all
return `false`, it returns `false`.
`any()` is short-circuiting; in other words, it will stop processing as soon as it finds a
`true`, given that no matter what else happens, the result will also be `true`.
An empty iterator returns `false`.
#### Signature
```rust theme={null}
fn any[Output: bool],
+Destruct,
+Destruct,
+Destruct,
>(
ref self: T, predicate: P,
) -> bool
```
#### Examples
Basic usage:
```rust theme={null}
assert!(array![1, 2, 3].into_iter().any(|x| x == 2));
assert!(!array![1, 2, 3].into_iter().any(|x| x > 5));
```
### all
Tests if every element of the iterator matches a predicate.
`all()` takes a closure that returns `true` or `false`. It applies this closure to each
element of the iterator, and if all of them return `true`, then so does `all()`. If any
of them return `false`, it returns `false`.
`all()` is short-circuiting; in other words, it will stop processing as soon as it finds a
`false`, given that no matter what else happens, the result will also be `false`.
An empty iterator returns `true`.
#### Signature
```rust theme={null}
fn all[Output: bool],
+Destruct,
+Destruct,
+Destruct,
>(
ref self: T, predicate: P,
) -> bool
```
#### Examples
Basic usage:
```rust theme={null}
assert!(array![1, 2, 3].into_iter().all(|x| x > 0));
assert!(!array![1, 2, 3].into_iter().all(|x| x > 2));
```
### find
Searches for an element of an iterator that satisfies a predicate.
`find()` takes a closure that returns `true` or `false`. It applies
this closure to each element of the iterator as a snapshot, and if
any of them return `true`, then `find()` returns `Some(element)`.
If they all return `false`, it returns [`None`](./core-option#none).
`find()` is short-circuiting; in other words, it will stop processing
as soon as the closure returns `true`.
#### Signature
```rust theme={null}
fn find[Output: bool], +Destruct, +Destruct, +Destruct>(ref self: T, predicate: P) -> OptionItem>
```
#### Examples
Basic usage:
```rust theme={null}
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(iter.find(|x| *x == 2), Option::Some(2));
assert_eq!(iter.find(|x| *x == 5), Option::None);
```
Stopping at the first `true`:
```rust theme={null}
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(iter.find(|x| *x == 2), Option::Some(2));
// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Option::Some(3));
```
Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
### filter
Creates an iterator which uses a closure to determine if an element
should be yielded. The closure takes each element as a snapshot.
Given an element the closure must return `true` or `false`. The returned
iterator will yield only the elements for which the closure returns
`true`.
#### Signature
```rust theme={null}
fn filter[Output: bool],
+Destruct,
+Destruct,
+Destruct,
>(
self: T, predicate: P,
) -> Filter
```
#### Examples
Basic usage:
```rust theme={null}
let a = array![0_u32, 1, 2];
let mut iter = a.into_iter().filter(|x| *x > 0);
assert_eq!(iter.next(), Option::Some(1));
assert_eq!(iter.next(), Option::Some(2));
assert_eq!(iter.next(), Option::None);
```
Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
### zip
'Zips up' two iterators into a single iterator of pairs.
`zip()` returns a new iterator that will iterate over two other
iterators, returning a tuple where the first element comes from the
first iterator, and the second element comes from the second iterator.
In other words, it zips two iterators together, into a single one.
If either iterator returns [`None`](./core-option#none), `next` from the zipped iterator
will return [`None`](./core-option#none).
If the zipped iterator has no more elements to return then each further attempt to advance
it will first try to advance the first iterator at most one time and if it still yielded an
item try to advance the second iterator at most one time.
#### Signature
```rust theme={null}
fn zip, +Destruct>(
self: T, other: U,
) -> Zip
```
#### Examples
Basic usage:
```rust theme={null}
let mut iter = array![1, 2, 3].into_iter().zip(array![4, 5, 6].into_iter());
assert_eq!(iter.next(), Some((1, 4)));
assert_eq!(iter.next(), Some((2, 5)));
assert_eq!(iter.next(), Some((3, 6)));
assert_eq!(iter.next(), None);
```
Since the argument to `zip()` uses [`IntoIterator`](./core-iter-traits-collect-IntoIterator), we can pass
anything that can be converted into an [`Iterator`](./core-iter-traits-iterator-Iterator), not just an
[`Iterator`](./core-iter-traits-iterator-Iterator) itself. For example:
```rust theme={null}
let mut iter = array![1, 2, 3].into_iter().zip(array![4, 5, 6]);
assert_eq!(iter.next(), Some((1, 4)));
assert_eq!(iter.next(), Some((2, 5)));
assert_eq!(iter.next(), Some((3, 6)));
assert_eq!(iter.next(), None);
```
### collect
Transforms an iterator into a collection.
`collect()` can take anything iterable, and turn it into a relevant
collection. This is one of the more powerful methods in the core
library, used in a variety of contexts.
The most basic pattern in which `collect()` is used is to turn one
collection into another. You take a collection, call `iter` on it,
do a bunch of transformations, and then `collect()` at the end.
`collect()` can also create instances of types that are not typical
collections.
Because `collect()` is so general, it can cause problems with type
inference. As such, `collect()` is one of the few times you'll see
the syntax affectionately known as the 'turbofish': `::<>`. This
helps the inference algorithm understand specifically which collection
you're trying to collect into.
#### Signature
```rust theme={null}
fn collect,
impl ItemEqual: TypeEqual::Item,
>,
+Destruct,
+FromIterator,
+Destruct,
>(
self: T,
) -> B
```
#### Examples
Basic usage:
```rust theme={null}
let doubled: Array = array![1, 2, 3].into_iter().map(|x| x * 2).collect();
assert_eq!(array![2, 4, 6], doubled);
```
Note that we needed the `: Array` on the left-hand side.
Using the 'turbofish' instead of annotating `doubled`:
```rust theme={null}
let doubled = array![1, 2, 3].into_iter().map(|x| x * 2).collect::>();
assert_eq!(array![2, 4, 6], doubled);
```
Because `collect()` only cares about what you're collecting into, you can
still use a partial type hint, `_`, with the turbofish:
```rust theme={null}
let doubled = array![1, 2, 3].into_iter().map(|x| x * 2).collect::>();
assert_eq!(array![2, 4, 6], doubled);
```
### peekable
Creates an iterator which can use the `peek` method to look at the next element of the
iterator. See its documentation for more information.
Note that the underlying iterator is still advanced when `peek` is called for the first
time: In order to retrieve the next element, `next` is called on the underlying iterator,
hence any side effects (i.e. anything other than fetching the next value) of the `next`
method will occur.
#### Signature
```rust theme={null}
fn peekable(self: T) -> PeekableItem>
```
#### Examples
Basic usage:
```rust theme={null}
let mut iter = (1..4_u8).into_iter().peekable();
// peek() lets us see one step into the future
assert_eq!(iter.peek(), Option::Some(1));
assert_eq!(iter.next(), Option::Some(1));
assert_eq!(iter.next(), Option::Some(2));
// we can peek() multiple times, the iterator won't advance
assert_eq!(iter.peek(), Option::Some(3));
assert_eq!(iter.peek(), Option::Some(3));
assert_eq!(iter.next(), Option::Some(3));프로젝트로 돌아가기