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

Rust Closures

Functions without a name that remember the variables around them.

  • ระดับสูง
  • อ่าน 3 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • |n| n * 2
  • Capturing variables
  • move and returning closures
Closure → result
|n| n * 2apply(21) → 42
|n| n + bonusapply(5) → 15
make_adder(5)add_five(1) → 6

A function that captures its surroundings

A closure is a function without a name that you can store in a variable or pass to another function. Unlike a normal function, it can use variables from the place where it was created.

|n| n * 2 is a closure with one parameter. add_bonus reads bonus from the surrounding code. move makes the closure own what it captures, which is needed when the closure is returned from make_adder. increment changes counter, so it must be declared mut.

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

  1. A closure can use variables from where it was created.
  2. move makes it own what it captures.
  3. A closure that changes a variable must be mut.

ตัวอย่าง Rust ที่รันได้

Rust
รันโค้ด →
main.rs
fn apply(value: i32, operation: impl Fn(i32) -> i32) -> i32 {
    operation(value)
}

fn make_adder(amount: i32) -> impl Fn(i32) -> i32 {
    move |value| value + amount
}

fn main() {
    let double = |n| n * 2;
    println!("{}", apply(21, double));

    let bonus = 10;
    let add_bonus = |n| n + bonus; // captures bonus from the environment
    println!("{}", apply(5, add_bonus));

    let add_five = make_adder(5);
    println!("{}", add_five(1));

    let mut counter = 0;
    let mut increment = || counter += 1;
    increment();
    increment();
    println!("counter = {counter}");
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
42
15
6
counter = 2

ฝึกฝน

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

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

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

ถัดไป: Modules and Visibility →

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

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

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