0Pricing
Learn Rust Coding · 강의

Iterator 트레이트

next와 지연 실행

Iterator 트레이트은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is an Iterator?

An iterator is anything that produces a sequence of values, one at a time. In Rust, iterators are the idiomatic way to process collections like vectors, ranges, and slices.

The whole concept is built on a single trait: Iterator. Once a type implements it, you get dozens of useful methods for free.

The Iterator Trait

The Iterator trait has one required method, next, and one associated type, Item:

  • type Item — the kind of value produced
  • fn next(&mut self) -> Option<Self::Item> — returns the next value

It returns Some(value) while values remain, then None when finished.

fn main() {
    let v = vec![10, 20, 30];
    let mut it = v.iter();
    println!("{:?}", it.next());
    println!("{:?}", it.next());
    println!("{:?}", it.next());
    println!("{:?}", it.next());
}

next Returns Option

Each call to next advances the iterator and hands you an Option. Some wraps a real value; None signals the end.

Notice that next takes &mut self — calling it changes internal state so the next call returns a different value.

fn main() {
    let mut it = (1..4).into_iter();
    while let Some(n) = it.next() {
        println!("got {}", n);
    }
    println!("done");
}

Iterators Are Lazy

Creating an iterator does nothing on its own. No values are computed until something asks for them. This is called laziness.

In the next example the map closure never runs, because we never consume the iterator.

fn main() {
    let nums = vec![1, 2, 3];
    let _doubled = nums.iter().map(|x| {
        println!("mapping {}", x);
        x * 2
    });
    println!("nothing printed above this line");
}

Consuming Triggers Work

To make a lazy iterator actually run, you consume it. A for loop is the simplest consumer: it calls next repeatedly until None.

Now the same map closure runs for every element.

fn main() {
    let nums = vec![1, 2, 3];
    for x in nums.iter().map(|x| x * 2) {
        println!("value {}", x);
    }
}

Three Ways to Iterate

Collections offer three iterator-producing methods:

  • iter() — yields &T (borrows)
  • iter_mut() — yields &mut T (mutable borrows)
  • into_iter() — yields T (takes ownership)
fn main() {
    let mut v = vec![1, 2, 3];
    for x in v.iter_mut() {
        *x += 10;
    }
    println!("{:?}", v);
}

for Loops Use into_iter

When you write for x in collection directly, Rust calls into_iter(), which consumes the collection.

After this loop you cannot use v again because it was moved into the iterator.

fn main() {
    let v = vec![String::from("a"), String::from("b")];
    for s in v {
        println!("{}", s);
    }
    // v is no longer usable here
}

Ranges Are Iterators

A range like 0..5 is itself an iterator producing 0, 1, 2, 3, 4. The end is exclusive. Use 0..=5 for an inclusive range.

Ranges are great for counting loops without manual index tracking.

fn main() {
    for i in 0..5 {
        print!("{} ", i);
    }
    println!();
    for i in 1..=3 {
        print!("{} ", i);
    }
    println!();
}

count: A Simple Consumer

count consumes the whole iterator and returns how many items it produced. It is one of many consuming adapters.

Because it consumes, you cannot reuse the iterator afterward.

fn main() {
    let total = (1..=100).count();
    println!("there are {} numbers", total);
}

sum: Folding Into One Value

sum adds every item together and returns a single value. You often annotate the target type so Rust knows what to produce.

This is more concise and clearer than a manual accumulator loop.

fn main() {
    let total: i32 = (1..=5).sum();
    println!("sum is {}", total);
}

Why Iterators Matter

Iterators give you composability: chain small operations into clear pipelines. They are also zero-cost — the compiler optimizes them to be as fast as hand-written loops.

Mastering next, laziness, and consumption is the foundation for everything that follows.

Quick Check

Test your understanding of the Iterator trait.

Recap

You learned the core of Rust iterators:

  • The Iterator trait needs only next and an Item type
  • next returns Some(value) then None
  • Iterators are lazy — they do nothing until consumed
  • iter, iter_mut, and into_iter control borrowing vs ownership
  • Consumers like for, count, and sum drive the work

자주 묻는 질문

“Iterator 트레이트” 강의는 무료인가요?

네 — “Iterator 트레이트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

“Iterator 트레이트”에서 뭘 배우나요?

next와 지연 실행 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“Iterator 트레이트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Iterator 트레이트
  2. map, filter, collect
  3. 어댑터와 소비자
  4. 사용자 정의 반복자
← Learn Rust Coding(으)로 돌아가기