You'll encounter closures when you want to spawn a thread, or when you want to do some functional programming with iterators and did some other common places in the standard library. So let's learn about closures. A closure is an anonymous function that can borrow or capture some data from the scope it is nested in. The syntax is a parameter list between two pipes without type annotations followed by a block. This creates an anonymous function called a closure that you can call later. The types of the arguments and the return value are all inferred from how you use the arguments and what you return.
So let's assign this closure to a variable called add and then call it with one and two, which will be added together and return three. Let's go back to our closure again. You don't have to have any parameters. You can just leave the parameter list empty. Technically, you can leave the block empty as well, but that's not very interesting. What is really interesting is that a closure will be borrow a reference to values in the enclosing scope.
Let's look at an example of that. Here we create a string s and then we create a closure that borrows a reference to s, which works because the print line macro actually wants a reference anyway. Then we assign the closure to the variable F, and whenever we call F, it prints a strawberry. This is great if your closure never outlives the variable that is referencing but the compiler won't let us send this over to another thread because another thread might live longer than this thread. Lucky for us closures also support move semantics. So we can force the closure to move any variables that uses into itself and take ownership of them.
Now S is owned by the closure and it will live until the closure itself goes out of scope and gets dropped. So we could send this closure over to another thread or return it as the value of a function or do whatever we want with it. If you want to do some functional style programming closures will be your close friends call ITER on a vector to get iterator and a whole bunch of methods that use closures will be available to you. Here's an example of using map and a closure to multiply each item in a vector by three, then filter in a closure to discard any values that aren't greater than 10 and then fold with an initial value and a closure to some the remaining values together. In the next video, we will talk about threats.