map, filter, collect
시퀀스 변환하기
map, filter, collect은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Transforming Sequences
Three methods do most of the work in iterator pipelines: map transforms each item, filter keeps some items, and collect gathers results into a collection.
Together they replace many manual loops with short, readable chains.
map: One In, One Out
map applies a closure to every item and yields the transformed value. The number of items stays the same; only their values change.
It is lazy, so the closure runs only when the iterator is consumed.
fn main() {
let nums = vec![1, 2, 3];
let doubled: Vec<i32> = nums.iter().map(|x| x * 2).collect();
println!("{:?}", doubled);
}map Can Change the Type
The output type of map does not have to match the input. Here we turn numbers into strings.
This makes map perfect for converting data from one shape to another.
fn main() {
let nums = vec![1, 2, 3];
let labels: Vec<String> = nums.iter().map(|x| format!("n{}", x)).collect();
println!("{:?}", labels);
}filter: Keep What You Want
filter takes a closure returning bool. Items where it returns true are kept; the rest are dropped.
The closure receives a reference, so you often dereference with * or use pattern matching.
fn main() {
let nums = vec![1, 2, 3, 4, 5, 6];
let evens: Vec<i32> = nums.into_iter().filter(|x| x % 2 == 0).collect();
println!("{:?}", evens);
}Chaining map and filter
You can chain adapters freely. Order matters: each item flows through the chain top to bottom.
Here we keep even numbers, then square the survivors.
fn main() {
let result: Vec<i32> = (1..=6)
.filter(|x| x % 2 == 0)
.map(|x| x * x)
.collect();
println!("{:?}", result);
}collect Into a Vec
collect consumes an iterator and builds a collection. Because many collection types are possible, you usually annotate the target type.
The turbofish syntax collect::<Vec<_>>() is an alternative to annotating the variable.
fn main() {
let squares = (1..=4).map(|x| x * x).collect::<Vec<i32>>();
println!("{:?}", squares);
}collect Into a String
collect is not limited to vectors. An iterator of char can collect into a String.
Rust uses the target type to decide how to assemble the items.
fn main() {
let shouted: String = "hello".chars().map(|c| c.to_ascii_uppercase()).collect();
println!("{}", shouted);
}collect Into a HashMap
An iterator of key-value tuples can collect into a HashMap. Pair items with zip or build tuples in a map.
This is a clean way to construct lookups from two parallel sequences.
use std::collections::HashMap;
fn main() {
let map: HashMap<i32, i32> = (1..=3).map(|x| (x, x * x)).collect();
println!("{:?}", map.get(&2));
}Combining All Three
A typical pipeline reads like a sentence: take items, filter them, map them, collect them.
Here we keep words longer than three letters and uppercase them.
fn main() {
let words = vec!["hi", "rust", "go", "code"];
let kept: Vec<String> = words
.into_iter()
.filter(|w| w.len() > 3)
.map(|w| w.to_uppercase())
.collect();
println!("{:?}", kept);
}filter_map: Filter and Map at Once
filter_map applies a closure returning Option. Some(v) is kept and unwrapped; None is dropped.
It shines when parsing, where some inputs may be invalid.
fn main() {
let inputs = vec!["1", "two", "3"];
let nums: Vec<i32> = inputs
.into_iter()
.filter_map(|s| s.parse::<i32>().ok())
.collect();
println!("{:?}", nums);
}Why This Pattern Wins
map/filter/collect pipelines are declarative: they say what you want, not how to loop. They avoid off-by-one bugs and intermediate mutable state.
And thanks to laziness, no temporary vectors are built between the steps.
Quick Check
Check what you know about transforming sequences.
Recap
You can now build real iterator pipelines:
maptransforms each item and may change its typefilterkeeps items whose predicate istruecollectgathers results intoVec,String,HashMap, and morefilter_mapfilters and maps in one step usingOption
자주 묻는 질문
“map, filter, collect” 강의는 무료인가요?
네 — “map, filter, collect” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.
“map, filter, collect”에서 뭘 배우나요?
시퀀스 변환하기 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“map, filter, collect” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Iterator 트레이트
- map, filter, collect
- 어댑터와 소비자
- 사용자 정의 반복자