Rust closure
Created By: chatGPT
Closures in Rust are anonymous functions that can capture the surrounding scope's variables. They offer a powerful and flexible way to work with functions as first-class objects. Understanding closures is essential for effective programming in Rust.
fn main() {
let x = 10;
let closure = |y| x + y;
let result = closure(5);
println!("Result: {}", result);
}
In the example above, we define a closure that takes one argument
y
. The closure captures the variable x
from its environment, allowing us to use it within its body. When we invoke the closure with the argument 5
, it returns 15
because it computes 10 + 5
.// Defining a closure using `Fn` trait
type AddFn = fn(i32) -> i32;
fn create_adder(x: i32) -> AddFn {
|y| x + y
}
fn main() {
let adder = create_adder(10);
let result = adder(5);
println!("Sum: {}", result);
}
Additionally, Rust provides three traits for closures based on how they capture variables: Fn, FnMut, and FnOnce. The
Fn
trait allows immutable borrowing, FnMut
allows mutable borrowing, and FnOnce
captures ownership of the captured variables. Here's how they differ:fn main() {
let mut num = 10;
// `FnMut` - allows mutable access
the mutator = |x| { num += x };
mutator(5);
println!("Num: {}", num);
// `FnOnce` - takes ownership of `num`
let take_ownership = move |y| num + y;
let sum = take_ownership(5);
println!("Sum with ownership: {}", sum);
}
To summarize, closures are a fundamental feature of Rust that allow for concise and powerful behavior in handling functions. They can capture variables from their environment and can be classified based on ownership and borrowing characteristics, making them adaptable for different scenarios.
// Example of different closure types
fn main() {
let x = 5;
let add = |y| x + y; // Borrowing
println!("Add: {}", add(10));
let mut counter = 0;
let increment = |n| { counter += n; };
increment(1);
println!("Counter: {}", counter);
}