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 रिव्यू के साथ।

सभी चैलेंज