Higher-order functions

We have seen previously how Rust functions define an isolated scope in which all local variables live. Thus, variables outside the scope can never leak into it unless they are explicitly passed as arguments. There can be cases where this is not the desired behavior; closures provide an anonymous function like mechanism, which has access to all the resources defined in the scope in which it is defined. This enables the compiler to enforce the same borrow checking rules while making it easier to reuse code. In Rust terminology, a typical closure borrows all bindings of its surrounding scope. A closure can be forced to own those by marking it with the move keyword. Let's look at some examples:

// chapter2/closure-borrow.rs ...

Get Network Programming with Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.