Iterators

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}");
    }
}
  • Iterator ํŠธ๋ ˆ์ž‡์€ ์ปฌ๋ ‰์…˜์— ๋Œ€ํ•œ ์—ฌ๋Ÿฌ ์ผ๋ฐ˜์ ์ธ ํ•จ์ˆ˜ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์ž‘์—…(์˜ˆ: map, filter, reduce ๋“ฑ)์„ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. ์ด๋Š” ๊ด€๋ จ ๋ฌธ์„œ๋ฅผ ๋ชจ๋‘ ์ฐพ์„ ์ˆ˜ ์žˆ๋Š” ํŠธ๋ ˆ์ž‡์ž…๋‹ˆ๋‹ค. Rust์—์„œ๋Š” ์ด๋Ÿฌํ•œ ํ•จ์ˆ˜๊ฐ€, ์ด์™€ ๋™์ผํ•œ ์ผ์„ ํ•˜๋Š” ๋ช…๋ นํ˜• ๊ตฌํ˜„๋งŒํผ ํšจ์œจ์ ์ธ ์ฝ”๋“œ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

  • IntoIterator๋Š” ๋ฃจํ”„๋ฅผ ์ž‘๋™ํ•˜๊ฒŒ ๋งŒ๋“œ๋Š” ํŠธ๋ ˆ์ž‡์ž…๋‹ˆ๋‹ค. ์ด๋Š” Vec<T>์™€ ๊ฐ™์€ ์ปฌ๋ ‰์…˜ ์œ ํ˜•๊ณผ &Vec<T> ๋ฐ &[T]์™€ ๊ฐ™์€ ์ด์— ๋Œ€ํ•œ ์ฐธ์กฐ์— ์˜ํ•ด ๊ตฌํ˜„๋ฉ๋‹ˆ๋‹ค. ๋ฒ”์œ„๋„ ์ด๋ฅผ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. ์ด๋Ÿฐ ์ด์œ ๋กœ for i in some_vec { .. }๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฒกํ„ฐ๋ฅผ ๋ฐ˜๋ณตํ•  ์ˆ˜ ์žˆ์ง€๋งŒ some_vec.next()๋Š” ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.