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()λŠ” μ‘΄μž¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.