Iterator
์ปฌ๋์
์ ์๋ ๊ฐ๋ค์ ์ ๊ทผํ๊ธฐ ์ํด์๋ Iterator
ํธ๋ ์์ ์ฌ์ฉํฉ๋๋ค. ์ด ํธ๋ ์์ next
๋ฉ์๋๋ฅผ ๋น๋กฏํ ๋ง์ ๋ฉ์๋๋ฅผ ์ ๊ณตํฉ๋๋ค. ๋ง์ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ ํ์
์ด Iterator
๋ฅผ ๊ตฌํํ๊ณ ์์ผ๋ฉฐ, ์ฌ๋ฌ๋ถ๋ ์ฌ๋ฌ๋ถ์ ํ์
์ด ์ด ํธ๋ ์์ ์ง์ ๊ตฌํํ๋๋ก ํ ์ ์์ต๋๋ค.
struct Fibonacci { curr: u32, next: u32, } impl Iterator for Fibonacci { type Item = u32; fn next(&mut self) -> Option<Self::Item> { let new_next = self.curr + self.next; self.curr = self.next; self.next = new_next; Some(self.curr) } } fn main() { let fib = Fibonacci { curr: 0, next: 1 }; for (i, n) in fib.enumerate().take(5) { println!("fib({i}): {n}"); } }
-
The
Iterator
trait implements many common functional programming operations over collections (e.g.map
,filter
,reduce
, etc). This is the trait where you can find all the documentation about them. In Rust these functions should produce the code as efficient as equivalent imperative implementations. -
IntoIterator
๋ ๋ฃจํ๋ฅผ ์๋ํ๊ฒ ๋ง๋๋ ํธ๋ ์์ ๋๋ค. ์ด๋Vec<T>
์ ๊ฐ์ ์ปฌ๋ ์ ํ์ ๊ณผ&Vec<T>
๋ฐ&[T]
์ ๊ฐ์ ์ด์ ๋ํ ์ฐธ์กฐ์ ์ํด ๊ตฌํ๋ฉ๋๋ค. ๋ฒ์๋ ์ด๋ฅผ ๊ตฌํํฉ๋๋ค. ์ด๋ฐ ์ด์ ๋กfor i in some_vec { .. }
๋ฅผ ์ฌ์ฉํ์ฌ ๋ฒกํฐ๋ฅผ ๋ฐ๋ณตํ ์ ์์ง๋งsome_vec.next()
๋ ์กด์ฌํ์ง ์์ต๋๋ค.