What’s a closure in Rust?
What’s a closure in Rust?
A closure in Rust is an anonymous function that can capture variables from its surrounding environment. Unlike regular functions, closures can access and manipulate variables that are in scope at the time they are defined. This makes them particularly useful for scenarios where you need to pass around bits of functionality that can operate on data available in the current context.
Anonymous Functions: Closures do not have a name and are defined using a syntax that involves vertical bars (|) to enclose parameters, followed by the function body. For example:
let add_one = |x| x + 1;
println!("{}", add_one(5)); // prints 6
Environment Capturing: Closures can capture variables from their surrounding scope. This can be done by reference, mutable reference, or by value, depending on how the closure is defined and used. Rust provides three traits to classify closures based on how they capture variables:
Fn: Captures variables by reference (&T).FnMut: Captures variables by mutable reference (&mut T).FnOnce: Captures variables by value (T).Syntax and Type Inference: The syntax for closures is more concise than for regular functions. Type annotations for parameters and return types are optional and can be inferred by the compiler. For example:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.