หัวข้อสำคัญของ Rust

Rust Iterators: map, filter, collect

Process a collection as a pipeline: keep some items, change them and gather the result.

  • ระดับสูง
  • อ่าน 3 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • iter, filter and map
  • collect and sum
  • enumerate and take
Even squares of 1 to 6
  1. 1iter()1 2 3 4 5 6
  2. 2filter2 4 6
  3. 3map4 16 36
  4. 4collect[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.

ประเด็นสำคัญ

  1. filter and map do nothing until a result is asked for.
  2. collect gathers the items into a Vec.
  3. 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}");
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
[4, 16, 36]
total = 21, max = Some(6)
0: 1
1: 2
any above 5: true

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Closures →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด