Closures Flashcards
What is a Closure
anonymous functions you can save in a variable or pass as arguments to other functions. You can create the closure in one place and then call the closure elsewhere to evaluate it in a different context. Unlike functions, closures can capture values from the scope in which they’re defined. We’ll demonstrate how these closure features allow for code reuse and behavior customization.
Benefits of using Closure
Enviroment Capture : able to get the variables in the scope of the closure
Flexible Parameter handling: unlike functions doesnt have to specify every single parameters.
Concise Syntax: Syntax for closure are very simple making it very readable for the developers
Type Inference: Closure are able to type infer
Disadvantages of using Closure
Memory Overhead: Closure are more costly than functions
Unclear lifetimes: like the move in thread spawn u have to be careful regarding lifetimes in closure
Complex type Signatures: Type signature can become complex in functions that have closure
Closure can capture their enviroment in various ways what is it?
three ways a function can take a parameter: borrowing immutably, borrowing mutably, and taking ownership.
What can Closure body do?
closure body can do any of the following: move a captured value out of the closure, mutate the captured value, neither move nor mutate the value, or capture nothing from the environment to begin with.
explain 3 differents Closure Fn traits
FnOnce applies to closures that can be called once. All closures implement at least this trait, because all closures can be called. A closure that moves captured values out of its body will only implement FnOnce and none of the other Fn traits, because it can only be called once.
FnMut applies to closures that don’t move captured values out of their body, but that might mutate the captured values. These closures can be called more than once.
Fn applies to closures that don’t move captured values out of their body and that don’t mutate captured values, as well as closures that capture nothing from their environment. These closures can be called more than once without mutating their environment, which is important in cases such as calling a closure multiple times concurrently.