Open In App

Rust – Higher Order Functions

Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we have a concept of Higher order functions that passes the function to another function once the variable is stored in another function. To define a function in Rust, we use the fn keyword.

Syntax:

fn <function name>()

{

}

Higher-order functions in Rust are those functions that take more than one function and produce more useful functions. once the functions are stored inside a variable, they are able to pass the function from one function to another.

For defining higher-order functions, there are traits that we need to import:

  • The map takes ‘inner’ values that can be mapped over by the variables.
  • sum() is used for the iteration of the iterables.
  • filter() is a struct that filters the elements of an iterator.
  • take_while() is a struct that takes an iterator and then returns a boolean value. 

Example:

Rust




// Rust code for Higher order function
fn check_odd(num: u32) -> bool {
    num % 2 == 1
}
  
fn main() {
let upper_limit = 10;
    println!("Sum of all squared numbers under {}",upper_limit);
      
    let squared_odd_numbers: u32 =
        (0..).map(|num| num * num)                             
             .take_while(|&num_squared| num_squared < upper_limit) 
             .filter(|&num_squared| check_odd(num_squared))    
             .sum();                                     
    println!("Value (functional approach): {}", squared_odd_numbers);
}


Output:

 

Explanation:

In this example, we have used a functional approach while checking a condition. Here, we have declared a upper_limit and initialized a value squared_odd_numbers (having 32-bit) and passed them inside a map with a condition that if all the numbers squared are below the upper limit then we would filter them (using the condition num_squared) then it would sum them. Finally, we print the value on the screen.


Last Updated : 22 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads