14.4 Iterators
Iterator trait은 배열과 같은 콜렉션에 반복자를 구현하기 위해 사용된다.
trait은 next 요소를 정의하는 메소드만 필요하며, 이는 수동으로 impl 블록을 정의되거나 자동으로 정의된다 (배열이나 범위들처럼).
편의성을 주 관점으로 일반적 상황에서, for 구문은 어떤 콜렉션을 반복자로 변환할 때 .into_iterator() 메소드를 사용한다.
아래 예제에서 보여주는 것 외에 Iterator trait을 사용하여 접근할 수 있는 메소드는 여기에서 찾을 수 있다.
struct Fibonacci {
curr: u32,
next: u32,
}
// `Fibonacci`에 대한 `Iterator` 구현
// `Iterator` trait은 `next`요소를 정의하는 메소드만 필요.
impl Iterator for Fibonacci {
type Item = u32;
// 여기서 `.curr`과 `.next`를 사용하여 시퀀스를 정의한다.
// 반환 타입은 `Option`이다:
// *`Iterator`가 끝나면 `None`이 반환된다.
// *그렇지 않으면, 다음 값은 `Some`으로 포장되어 반환된다.
fn next(&mut self) -> Option<u32> {
let new_next = self.curr + self.next;
self.curr = self.next;
self.next = new_next;
// 피보나치 연속은 끝나지 않으므로
// `None`은 절대 반환되지 않고 `Some`이 늘 반환된다.
Some(self.curr)
}
}
// 피보나치 반복 생성자를 반환.
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 1, next: 1 }
}
fn main() {
// `0...3`은 0, 1, 그리고 2를 생성하는 `Iterator`이다.
let mut sequence = 0..3;
println!("Four consecutive `next` calls on 0..3");
println!("> {:?}", sequence.next());
println!("> {:?}", sequence.next());
println!("> {:?}", sequence.next());
println!("> {:?}", sequence.next());
// `for`는 `None`을 반환 할 때까지 `Iterator`를 통해 동작한다.
// 각 `Some`값은 포장을 벗겨 변수에 바인드한다(여기서는, `i`).
println!("Iterate through 0..3 using `for`");
for i in 0..3 {
println!("> {}", i);
}
// `take(n)`메소드는 `Iterator`를 `n`번째 항까지로 경감한다.
println!("The first four terms of the Fibonacci sequence are: ");
for i in fibonacci().take(4) {
println!("> {}", i);
}
// `skip(n)`메소드는 처음부터 `n`항까지 버려서 `Iterator`를 단축한다.
println!("The next four terms of the Fibonacci sequence are: ");
for i in fibonacci().skip(4).take(4) {
println!("> {}", i);
}
let array = [1u32, 3, 3, 7];
// `iter`메소드는 배열/조각의 `Iterator`를 생성한다.
println!("Iterate the following array {:?}", &array);
for i in array.iter() {
println!("> {}", i);
}
}