Rust 주요 주제
Rust Iterators: map, filter, collect
Process a collection as a pipeline: keep some items, change them and gather the result.
배울 내용
- iter, filter and map
- collect and sum
- enumerate and take
Even squares of 1 to 6
- 1
iter()1 2 3 4 5 6 - 2
filter2 4 6 - 3
map4 16 36 - 4
collect[4, 16, 36]
A lazy pipeline
An iterator produces the items of a collection one at a time. Methods such as filter and map build a new iterator, and methods such as collect and sum run it and produce a result.
Iterators are lazy: filter and map do nothing until collect asks for the items. sum needs the result type, here i32. max returns an Option because the list could be empty. enumerate adds the index and take(2) stops after two items.
핵심 포인트
- filter and map do nothing until a result is asked for.
- collect gathers the items into a Vec.
- max returns an Option.
실행 가능한 Rust 예제
Rust
main.rs
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let even_squares: Vec<i32> = numbers
.iter()
.filter(|n| *n % 2 == 0)
.map(|n| n * n)
.collect();
println!("{:?}", even_squares);
let total: i32 = numbers.iter().sum();
let max = numbers.iter().max();
println!("total = {total}, max = {:?}", max);
for (index, value) in numbers.iter().enumerate().take(2) {
println!("{index}: {value}");
}
let any_big = numbers.iter().any(|&n| n > 5);
println!("any above 5: {any_big}");
}
[4, 16, 36]
total = 21, max = Some(6)
0: 1
1: 2
any above 5: true연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- Above-Average Values Keep the values that are greater than the average. 쉬움
- 중복 제거 각 값의 첫 번째 등장만 남기세요. 쉬움