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}");
    }
}
This slide should take about 5 minutes.
  • 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()๋Š” ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.