Chủ đề Rust quan trọng
Rust Iterators: map, filter, collect
Process a collection as a pipeline: keep some items, change them and gather the result.
Bạn sẽ học được gì
- 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.
Những điểm quan trọng
- filter and map do nothing until a result is asked for.
- collect gathers the items into a Vec.
- max returns an Option.
Ví dụ Rust chạy được
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: trueLuyện tập
Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.
Bạn học xong bài này chưa?
Đánh dấu đã học để theo dõi tiến độ của bạn.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
- Above-Average Values Keep the values that are greater than the average. Dễ
- Loại Bỏ Phần Tử Trùng Lặp Chỉ giữ lại lần xuất hiện đầu tiên của mỗi giá trị. Dễ