Learn Rust Β· 9/14

Functional Language Features

7 min read

Functional Language Features in Rust πŸ¦€

Welcome back! Today, we're diving into some of the powerful functional programming features that Rust offers. Don't worry, it's not as scary as it sounds. Think of it as adding some new, super-efficient tools to your Rust toolbox. These features allow you to write more concise, expressive, and often faster code.


1. Closures: Anonymous Functions that Capture Their Environment πŸ•΅οΈ

Definition: A closure is an anonymous function that you can save in a variable or pass as an argument to other functions. Unlike functions, closures can capture values from the scope in which they are defined.

The Problem: Imagine you need a small, one-off function inside another function. Maybe you're sorting a list of numbers in a special way that depends on a local variable. Defining a whole separate named function for this small task can feel clunky and pollute the namespace. Also, how would that separate function access the local variable it needs?

The Solution: Closures to the rescue! They are like little "private" functions that you can create on the fly, and they have a special power: they can "remember" and access variables from their surrounding environment.

Let's look at the syntax. It's a bit different from a regular fn.

rust
|param1, param2| {
    // code
}

The parameters are listed between the pipes | |, and the body is in the curly braces {}. For very short closures, you can even skip the curly braces.

Capturing the Environment

This is the superpower of closures. They can "capture" variables from their enclosing scope in three ways:

  1. Borrowing immutably (&T): The closure borrows the value without changing it.
  2. Borrowing mutably (&mut T): The closure can modify the borrowed value.
  3. Taking ownership (move): The closure takes ownership of the value.

Rust is smart and will infer the most efficient way to capture the variable. You can force the closure to take ownership by using the move keyword before the parameters.

A Simple Example:

Let's say we have a list of numbers and we want to add a specific value to each of them.

rust
fn main() {
    let list_of_numbers = vec![1, 2, 3];
    let number_to_add = 5;

    // This closure captures `number_to_add` from its environment
    let add_five = |x| x + number_to_add;

    let new_list: Vec<_> = list_of_numbers.iter().map(add_five).collect();

    println!("Original list: {:?}", list_of_numbers);
    println!("New list: {:?}", new_list);
}

In this example, the add_five closure captures number_to_add. If we didn't have closures, this would be more complicated to write.

Interesting Fact: The name "closure" comes from the concept of "closing over" the variables from the environment. It's like the closure creates a self-contained little package with the code and the data it needs to run.


2. Iterators: Processing a Series of Items πŸšΆβ€β™€οΈπŸšΆβ€β™‚οΈ

Definition: An iterator is a construct that allows you to perform a sequence of operations on a collection of items. In Rust, an iterator is anything that implements the Iterator trait.

The Problem: You have a collection of items, like a Vec or a HashMap. How do you go through each item and do something with it? The classic way is to use a for loop with an index.

rust
let numbers = vec![10, 20, 30];
for i in 0..numbers.len() {
    println!("The number is {}", numbers[i]);
}

This works, but it's a bit verbose and can be prone to errors (like getting the index wrong). It also doesn't express the intent of what you're doing very clearly.

The Solution: Iterators provide a more abstract and powerful way to handle sequences of data. When you use an iterator, you don't have to worry about indexing or managing the state of the iteration.

The core of the Iterator trait is the next() method, which returns the next item in the sequence wrapped in an Some, or None when the sequence is finished.

You can create an iterator from a collection in a few ways:

  • .iter(): Creates an iterator that borrows each element of the collection.
  • .iter_mut(): Creates an iterator that mutably borrows each element, allowing you to modify them.
  • .into_iter(): Creates an iterator that takes ownership of the collection and returns owned values.

Example with .iter():

rust
fn main() {
    let names = vec!["Alice", "Bob", "Charlie"];

    let names_iterator = names.iter();

    for name in names_iterator {
        println!("Hello, {}!", name);
    }
}

This is much cleaner and safer than the manual indexing loop!

Iterators are also "lazy," which means they don't do any work until you actually consume them (for example, by using them in a for loop or calling a method like collect()).


3. Performance of Iterators: Zero-Cost Abstractions πŸš€

A common concern with high-level abstractions like iterators is performance. If you write a for loop, you know it's going to be fast. But what about all these iterator methods like map, filter, etc.?

The Concept: In Rust, many of the high-level features are designed to be "zero-cost abstractions." This means that using the abstraction doesn't impose any additional runtime overhead compared to writing the equivalent low-level code yourself.

How does Rust do it? The magic lies in the compiler. When you compile your Rust code with optimizations (--release flag), the compiler takes your iterator chains and turns them into highly efficient, low-level machine code. It essentially "unrolls" the iterators and inlines the closures, resulting in code that's often just as fast as a handwritten for loop.

Let's look at a simple example:

rust
// High-level code with iterators
pub fn add_one_to_each(numbers: &mut [i32]) {
    for num in numbers.iter_mut() {
        *num += 1;
    }
}

// What the compiler might generate (simplified)
pub fn add_one_to_each_compiled(numbers: &mut [i32]) {
    let mut i = 0;
    while i < numbers.len() {
        numbers[i] = numbers[i] + 1;
        i += 1;
    }
}

Because of this, you can write beautiful, expressive code using iterators without having to worry about sacrificing performance. It's like having your cake and eating it too! πŸŽ‚


4. Practical Functional Patterns in Rust πŸ› οΈ

Now let's get to the really fun part: using iterator methods to perform common data processing tasks. These methods are often called "iterator adaptors" because they take an iterator and return a new one with a different behavior.

Here are some of the most frequently used ones:

  • map: Transforms each item in the iterator.
  • filter: Keeps only the items that satisfy a certain condition.
  • fold: Combines all the items into a single value.
  • collect: Gathers all the items into a new collection.

Real-world Scenario: E-commerce Order Processing

Imagine you have a list of products in a shopping cart, and you need to calculate the total price of all the products that are in stock.

rust
struct Product {
    name: String,
    price: f64,
    in_stock: bool,
}

fn main() {
    let cart = vec![
        Product { name: "Laptop".to_string(), price: 1200.0, in_stock: true },
        Product { name: "Mouse".to_string(), price: 25.0, in_stock: false },
        Product { name: "Keyboard".to_string(), price: 75.0, in_stock: true },
        Product { name: "Monitor".to_string(), price: 300.0, in_stock: true },
    ];

    let total_price: f64 = cart
        .iter() // Create an iterator over the cart
        .filter(|p| p.in_stock) // Keep only the products that are in stock
        .map(|p| p.price) // Get the price of each product
        .sum(); // Sum up all the prices

    println!("Total price of in-stock items: ${}", total_price);
}

Look at how clean and readable that is! You can clearly see the steps: iterate, filter, map, and then sum. This is a common pattern you'll see in Rust code.

By chaining these methods, you can build up complex data processing pipelines in a very declarative way. You're describing what you want to do, not the nitty-gritty details of how to do it.


Further Reading πŸ“š

Challenge

You are given a User struct that represents a user with an id, is_active status, and a score.

Your task is to implement the function calculate_promotional_score. This function takes a slice of User objects and should return the total promotional score based on the following rules, using a single chained iterator expression:

  1. Start with an iterator over the input slice.
  2. Filter the users to include only those who are is_active.
  3. From the active users, further filter to include only those with a score of 50 or greater.
  4. For each of the remaining users, transform their score by doubling it.
  5. Finally, calculate the sum of all the resulting scores.

Expected result

The implementation should use the iter() method to create an iterator over the users slice. This must be followed by a chain of iterator adaptors (filter, map) and a consuming adaptor (sum) to perform the required logic. The logic within the adaptors should be implemented using closures.

The correct implementation is a single return statement inside the function body:

rust
users
    .iter()
    .filter(|user| user.is_active && user.score >= 50)
    .map(|user| user.score * 2)
    .sum()

An acceptable alternative is to chain two separate filter calls:

rust
users
    .iter()
    .filter(|user| user.is_active)
    .filter(|user| user.score >= 50)
    .map(|user| user.score * 2)
    .sum()
rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.