← Back to Rust Course | Chapter 4: Functions | Lesson 5 of 6

Higher-Order Functions क्या हैं

एक higher-order function वह है जो अपना input के रूप में दूसरा function या closure ले सकता है, या अपना answer के रूप में एक वापस दे सकता है।
Syntax
rust
fn name<F>(f: F) -> ReturnType
where
    F: Fn(ParamType) -> ReturnType,
{
    f(value)
}

Passing a Closure as a Parameter

एक function Fn(i32) -> i32 जैसे trait bound specify करके एक closure को parameter के रूप में accept कर सकता है, जो किसी भी callable को describe करता है जो एक i32 लेता है और एक i32 return करता है।

उदाहरण: Passing a Closure as a Parameter

markup
fn apply_twice<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
    f(f(x))
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `result`, set to `apply_twice(|n| n + 3, 10)`
    let result = apply_twice(|n| n + 3, 10);
    // Print "{}" to the console, substituting in `result` (with a trailing newline)
    println!("{}", result);
}

Using map with a Closure

Standard library का iterators पर .map() method एक higher-order function है: यह एक closure लेता है और इसे हर element पर apply करता है, transformed values का एक नया iterator produce करते हुए।

उदाहरण: Using map with a Closure

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `numbers`, set to `vec![1, 2, 3]`
    let numbers = vec![1, 2, 3];
    // Declare an immutable variable `doubled` (a `Vec<i32>`), set to `numbers.iter().map(|n| n * 2).collect()`
    let doubled: Vec<i32> = numbers.iter().map(|n| n * 2).collect();
    // Print "{:?}" to the console, substituting in `doubled` (with a trailing newline)
    println!("{:?}", doubled);
}

Returning a Closure

Functions closures भी return कर सकते हैं, आमतौर पर Box<dyn Fn(...) -> ...> के पीछे boxed किए गए क्योंकि closures के unique, unnamed types होते हैं जिन्हें return करने के लिए एक trait object में capture किया जाना चाहिए।

उदाहरण: Returning a Closure

markup
// Define the function `make_adder` taking `amount` and returning a `Box<dyn Fn(i32) -> i32>`
fn make_adder(amount: i32) -> Box<dyn Fn(i32) -> i32> {
    Box::new(move |x| x + amount)
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `add_five`, set to `make_adder(5)`
    let add_five = make_adder(5);
    // Print "{}" to the console, substituting in `add_five(10)` (with a trailing newline)
    println!("{}", add_five(10));
}

Passing a Named Function Instead of a Closure

चूंकि plain functions और captures न रखने वाले closures compatible shape share करते हैं, आप जहां भी एक matching closure type expected हो वहां सीधे एक named function pass कर सकते हैं।

उदाहरण: Passing a Named Function Instead of a Closure

markup
// Define the function `triple` taking `x` and returning an integer
fn triple(x: i32) -> i32 {
    x * 3
}

// Define the function `apply` taking `f`, `value` and returning an integer
fn apply(f: fn(i32) -> i32, value: i32) -> i32 {
    f(value)
}

// Entry point: execution of the program starts here
fn main() {
    // Print "{}" to the console, substituting in `apply(triple, 4)` (with a trailing newline)
    println!("{}", apply(triple, 4));
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक closure parameter accept करने वाला function लिखते समय closure trait bound (Fn, FnMut, या FnOnce) specify करना भूल जाना।
  2. यह मान लेना कि closures और function pointers हर generic context में बिल्कुल interchangeable हैं, जब उनके trait bounds subtly अलग हैं।
  3. साधारण logic को higher-order functions से overcomplicate करना जब एक plain loop code पढ़ने वाले beginners के लिए clearer होता।
चैप्टर सारांश
  • एक function जो एक closure या दूसरा function parameter के रूप में accept करता है उसे higher-order function कहते हैं।
  • Fn trait bound एक closure को describe करता है जिसे captured variables consume किए बिना बार-बार call किया जा सकता है।
  • .map() और .filter() जैसे standard library methods closures लेने वाले higher-order functions हैं।
  • Function pointers (fn(i32) -> i32) भी closures की तरह values की तरह pass किए जा सकते हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.