Sophie

Sophie

distrib > Mageia > 6 > x86_64 > media > core-updates > by-pkgid > 878cdd00a13d17a73c6619a777ef5d74 > files > 275

rust-doc-1.19.0-1.mga6.x86_64.rpm

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Closures - The Rust Programming Language</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <base href="">

        <link rel="stylesheet" href="book.css">
        <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

        <link rel="shortcut icon" href="favicon.png">

        <!-- Font Awesome -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <style>
            .page-wrapper.has-warning > .nav-chapters {
              /* add height for warning content & margin */
              top: 120px;
            }

            p.warning {
                background-color: rgb(242, 222, 222);
                border-bottom-color: rgb(238, 211, 215);
                border-bottom-left-radius: 4px;
                border-bottom-right-radius: 4px;
                border-bottom-style: solid;
                border-bottom-width: 0.666667px;
                border-image-outset: 0 0 0 0;
                border-image-repeat: stretch stretch;
                border-image-slice: 100% 100% 100% 100%;
                border-image-source: none;
                border-image-width: 1 1 1 1;
                border-left-color: rgb(238, 211, 215);
                border-left-style: solid;
                border-left-width: 0.666667px;
                border-right-color: rgb(238, 211, 215);
                border-right-style: solid;
                border-right-width: 0.666667px;
                border-top-color: rgb(238, 211, 215);
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                border-top-style: solid;
                border-top-width: 0.666667px;
                color: rgb(185, 74, 72);
                margin-bottom: 0px;
                margin-left: 0px;
                margin-right: 0px;
                margin-top: 30px;
                padding-bottom: 8px;
                padding-left: 14px;
                padding-right: 35px;
                padding-top: 8px;
            }
            p.warning strong {
                color: rgb(185, 74, 72)
            }
            p.warning a {
                color: rgb(0, 136, 204)
            }
        </style>

        <!-- MathJax -->
        <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

        <!-- Fetch JQuery from CDN but have a local fallback -->
        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script>
            if (typeof jQuery == 'undefined') {
                document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
            }
        </script>
    </head>
    <body class="light">
        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme = localStorage.getItem('theme');
            if (theme == null) { theme = 'light'; }
            $('body').removeClass().addClass(theme);
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var sidebar = localStorage.getItem('sidebar');
            if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
            else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
        </script>

        <div id="sidebar" class="sidebar">
            <ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> Common Programming Concepts</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> Variables and Mutability</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> Data Types</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> How Functions Work</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> Control Flow</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> What is Ownership?</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References &amp; Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> Using Structs to Structure Related Data</a></li><li><ul class="section"><li><a href="ch05-01-defining-structs.html"><strong>5.1.</strong> Defining and Instantiating Structs</a></li><li><a href="ch05-02-example-structs.html"><strong>5.2.</strong> An Example Program Using Structs</a></li><li><a href="ch05-03-method-syntax.html"><strong>5.3.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums and Pattern Matching</a></li><li><ul class="section"><li><a href="ch06-01-defining-an-enum.html"><strong>6.1.</strong> Defining an Enum</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> The <code>match</code> Control Flow Operator</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> Concise Control Flow with <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing Names with <code>use</code></a></li></ul></li><li><a href="ch08-00-common-collections.html"><strong>8.</strong> Common Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> Error Handling</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> Unrecoverable Errors with <code>panic!</code></a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> Recoverable Errors with <code>Result</code></a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> To <code>panic!</code> or Not To <code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> Generic Types, Traits, and Lifetimes</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> Generic Data Types</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> Traits: Defining Shared Behavior</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> Validating References with Lifetimes</a></li></ul></li><li><a href="ch11-00-testing.html"><strong>11.</strong> Testing</a></li><li><ul class="section"><li><a href="ch11-01-writing-tests.html"><strong>11.1.</strong> Writing tests</a></li><li><a href="ch11-02-running-tests.html"><strong>11.2.</strong> Running tests</a></li><li><a href="ch11-03-test-organization.html"><strong>11.3.</strong> Test Organization</a></li></ul></li><li><a href="ch12-00-an-io-project.html"><strong>12.</strong> An I/O Project</a></li><li><ul class="section"><li><a href="ch12-01-accepting-command-line-arguments.html"><strong>12.1.</strong> Accepting Command Line Arguments</a></li><li><a href="ch12-02-reading-a-file.html"><strong>12.2.</strong> Reading a File</a></li><li><a href="ch12-03-improving-error-handling-and-modularity.html"><strong>12.3.</strong> Improving Error Handling and Modularity</a></li><li><a href="ch12-04-testing-the-librarys-functionality.html"><strong>12.4.</strong> Testing the Library's Functionality</a></li><li><a href="ch12-05-working-with-environment-variables.html"><strong>12.5.</strong> Working with Environment Variables</a></li><li><a href="ch12-06-writing-to-stderr-instead-of-stdout.html"><strong>12.6.</strong> Writing to <code>stderr</code> instead of <code>stdout</code></a></li></ul></li><li><a href="ch13-00-functional-features.html"><strong>13.</strong> Functional Language Features in Rust</a></li><li><ul class="section"><li><a href="ch13-01-closures.html" class="active"><strong>13.1.</strong> Closures</a></li><li><a href="ch13-02-iterators.html"><strong>13.2.</strong> Iterators</a></li><li><a href="ch13-03-improving-our-io-project.html"><strong>13.3.</strong> Improving our I/O Project</a></li><li><a href="ch13-04-performance.html"><strong>13.4.</strong> Performance</a></li></ul></li><li><a href="ch14-00-more-about-cargo.html"><strong>14.</strong> More about Cargo and Crates.io</a></li><li><ul class="section"><li><a href="ch14-01-release-profiles.html"><strong>14.1.</strong> Release Profiles</a></li><li><a href="ch14-02-publishing-to-crates-io.html"><strong>14.2.</strong> Publishing a Crate to Crates.io</a></li><li><a href="ch14-03-cargo-workspaces.html"><strong>14.3.</strong> Cargo Workspaces</a></li><li><a href="ch14-04-installing-binaries.html"><strong>14.4.</strong> Installing Binaries from Crates.io with <code>cargo install</code></a></li><li><a href="ch14-05-extending-cargo.html"><strong>14.5.</strong> Extending Cargo with Custom Commands</a></li></ul></li><li><a href="ch15-00-smart-pointers.html"><strong>15.</strong> Smart Pointers</a></li><li><ul class="section"><li><a href="ch15-01-box.html"><strong>15.1.</strong> <code>Box&lt;T&gt;</code> Points to Data on the Heap and Has a Known Size</a></li><li><a href="ch15-02-deref.html"><strong>15.2.</strong> The <code>Deref</code> Trait Allows Access to the Data Through a Reference</a></li><li><a href="ch15-03-drop.html"><strong>15.3.</strong> The <code>Drop</code> Trait Runs Code on Cleanup</a></li><li><a href="ch15-04-rc.html"><strong>15.4.</strong> <code>Rc&lt;T&gt;</code>, the Reference Counted Smart Pointer</a></li><li><a href="ch15-05-interior-mutability.html"><strong>15.5.</strong> <code>RefCell&lt;T&gt;</code> and the Interior Mutability Pattern</a></li><li><a href="ch15-06-reference-cycles.html"><strong>15.6.</strong> Creating Reference Cycles and Leaking Memory is Safe</a></li></ul></li><li><a href="ch16-00-concurrency.html"><strong>16.</strong> Fearless Concurrency</a></li><li><ul class="section"><li><a href="ch16-01-threads.html"><strong>16.1.</strong> Threads</a></li><li><a href="ch16-02-message-passing.html"><strong>16.2.</strong> Message Passing</a></li><li><a href="ch16-03-shared-state.html"><strong>16.3.</strong> Shared State</a></li><li><a href="ch16-04-extensible-concurrency-sync-and-send.html"><strong>16.4.</strong> Extensible Concurrency: <code>Sync</code> and <code>Send</code></a></li></ul></li><li><a href="ch17-00-oop.html"><strong>17.</strong> Is Rust an Object-Oriented Programming Language?</a></li><li><ul class="section"><li><a href="ch17-01-what-is-oo.html"><strong>17.1.</strong> What Does Object-Oriented Mean?</a></li><li><a href="ch17-02-trait-objects.html"><strong>17.2.</strong> Trait Objects for Using Values of Different Types</a></li><li><a href="ch17-03-oo-design-patterns.html"><strong>17.3.</strong> Object-Oriented Design Pattern Implementations</a></li></ul></li><li><a href="ch18-00-patterns.html"><strong>18.</strong> Patterns Match the Structure of Values</a></li><li><ul class="section"><li><a href="ch18-01-all-the-places-for-patterns.html"><strong>18.1.</strong> All the Places Patterns May be Used</a></li><li><a href="ch18-02-refutability.html"><strong>18.2.</strong> Refutability: Whether a Pattern Might Fail to Match</a></li><li><a href="ch18-03-pattern-syntax.html"><strong>18.3.</strong> All the Pattern Syntax</a></li></ul></li><li><a href="ch19-00-advanced-features.html"><strong>19.</strong> Advanced Features</a></li><li><ul class="section"><li><a href="ch19-01-unsafe-rust.html"><strong>19.1.</strong> Unsafe Rust</a></li><li><a href="ch19-02-advanced-lifetimes.html"><strong>19.2.</strong> Advanced Lifetimes</a></li><li><a href="ch19-03-advanced-traits.html"><strong>19.3.</strong> Advanced Traits</a></li><li><a href="ch19-04-advanced-types.html"><strong>19.4.</strong> Advanced Types</a></li><li><a href="ch19-05-advanced-functions-and-closures.html"><strong>19.5.</strong> Advanced Functions &amp; Closures</a></li></ul></li><li><a href="ch20-00-final-project-a-web-server.html"><strong>20.</strong> Final Project: Building a Multithreaded Web Server</a></li><li><ul class="section"><li><a href="ch20-01-single-threaded.html"><strong>20.1.</strong> A Single Threaded Web Server</a></li><li><a href="ch20-02-slow-requests.html"><strong>20.2.</strong> How Slow Requests Affect Throughput</a></li><li><a href="ch20-03-designing-the-interface.html"><strong>20.3.</strong> Designing the Thread Pool Interface</a></li><li><a href="ch20-04-storing-threads.html"><strong>20.4.</strong> Creating the Thread Pool and Storing Threads</a></li><li><a href="ch20-05-sending-requests-via-channels.html"><strong>20.5.</strong> Sending Requests to Threads Via Channels</a></li><li><a href="ch20-06-graceful-shutdown-and-cleanup.html"><strong>20.6.</strong> Graceful Shutdown and Cleanup</a></li></ul></li><li><a href="appendix-00.html"><strong>21.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>21.1.</strong> A - Keywords</a></li><li><a href="appendix-02-operators.html"><strong>21.2.</strong> B - Operators</a></li><li><strong>21.3.</strong> C - Derivable Traits</li><li><strong>21.4.</strong> D - Nightly Rust</li><li><strong>21.5.</strong> E - Macros</li><li><strong>21.6.</strong> F - Translations</li><li><a href="appendix-07-newest-features.html"><strong>21.7.</strong> G - Newest Features</a></li></ul></li></ul>
        </div>

        <div id="page-wrapper" class="page-wrapper has-warning">

            <div class="page">
                <header><p class="warning">You are reading a <strong>draft</strong> of the next edition of TRPL. For more, go <a href="../index.html">here</a>.</p></header>
                <div id="menu-bar" class="menu-bar">
                    <div class="left-buttons">
                        <i id="sidebar-toggle" class="fa fa-bars"></i>
                        <i id="theme-toggle" class="fa fa-paint-brush"></i>
                    </div>

                    <h1 class="menu-title">The Rust Programming Language</h1>

                    <div class="right-buttons">
                        <i id="print-button" class="fa fa-print" title="Print this book"></i>
                    </div>
                </div>


                <div id="content" class="content">
                    <a class="header" href="ch13-01-closures.html#closures-anonymous-functions-that-can-capture-their-environment" id="closures-anonymous-functions-that-can-capture-their-environment"><h2>Closures: Anonymous Functions that can Capture their Environment</h2></a>
<!-- Bill's suggested we flesh out some of these subtitles, which I think we
did more with earlier chapters but we (I, included!) have got a bit lax with. I
don't think this is quite right, is there a shorter heading we could use to
capture what a closure is/is for? -->
<!-- I've attempted a more descriptive subtitle, what do you think? /Carol -->
<p>Rust's <em>closures</em> are anonymous functions that 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 to evaluate it in a different context. Unlike
functions, closures are allowed to capture values from the scope in which they
are called. We're going to demonstrate how these features of closures allow for
code reuse and customization of behavior.</p>
<!-- Can you say what sets closures apart from functions, explicitly, above? I
can't see it clearly enough to be confident, after one read through this
chapter. I think it would help to have the closure definition up front, to help
to let the reader know what they are looking out for in the examples. When
would you use a closure, for example, rather than using a function? And is it
the closure that's stored in the variable, or is it the result of applying the
closure to a value passed as an argument? -->
<!-- I've tried reworking the above paragraph and restructuring the examples to
be more motivating. I've also tried to make it clear throughout that storing a
closure is storing the *unevaluated* code, and then you call the closure in
order to get the result. /Carol -->
<a class="header" href="ch13-01-closures.html#creating-an-abstraction-of-behavior-using-a-closure" id="creating-an-abstraction-of-behavior-using-a-closure"><h3>Creating an Abstraction of Behavior Using a Closure</h3></a>
<p>Let's work on an example that will show a situation where storing a closure to
be executed at a later time is useful. We'll talk about the syntax of closures,
type inference, and traits along the way.</p>
<p>The hypothetical situation is this: we're working at a startup that's making an
app to generate custom exercise workout plans. The backend is written in Rust,
and the algorithm that generates the workout plan takes into account many
different factors like the app user's age, their Body Mass Index, their
preferences, their recent workouts, and an intensity number they specify. The
actual algorithm used isn't important in this example; what's important is that
this calculation takes a few seconds. We only want to call this algorithm if we
need to, and we only want to call it once, so that we aren't making the user
wait more than they need to. We're going to simulate calling this hypothetical
algorithm by calling the <code>simulated_expensive_calculation</code> function shown in
Listing 13-1 instead, which will print <code>calculating slowly...</code>, wait for two
seconds, and then return whatever number we passed in:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
use std::thread;
use std::time::Duration;

fn simulated_expensive_calculation(intensity: i32) -&gt; i32 {
    println!(&quot;calculating slowly...&quot;);
    thread::sleep(Duration::from_secs(2));
    intensity
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-1: A function we'll use to stand in for a
hypothetical calculation that takes about two seconds to run</span></p>
<p>Next, we have a <code>main</code> function that contains the parts of the workout app that
are important for this example. This represents the code that the app would
call when a user asks for a workout plan. Because the interaction with the
app's frontend isn't relevant to the use of closures, we're going to hardcode
values representing inputs to our program and print the outputs.</p>
<p>The inputs to the program are:</p>
<ul>
<li>An <code>intensity</code> number from the user, specified when they request a workout,
so they can indicate whether they'd like a low intensity workout or a high
intensity workout</li>
<li>A random number that will generate some variety in the workout plans</li>
</ul>
<p>The output the program prints will be the recommended workout plan.</p>
<p>Listing 13-2 shows the <code>main</code> function we're going to use. We've hardcoded the
variable <code>simulated_user_specified_value</code> to 10 and the variable
<code>simulated_random_number</code> to 7 for simplicity's sake; in an actual program we'd
get the intensity number from the app frontend and we'd use the <code>rand</code> crate to
generate a random number like we did in the Guessing Game example in Chapter 2.
The <code>main</code> function calls a <code>generate_workout</code> function with the simulated
input values:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust">fn main() {
    let simulated_user_specified_value = 10;
    let simulated_random_number = 7;

    generate_workout(simulated_user_specified_value, simulated_random_number);
}
# fn generate_workout(intensity: i32, random_number: i32) {}
</code></pre></pre>
<p><span class="caption">Listing 13-2: A <code>main</code> function containing hardcoded
values to simulate user input and random number generation inputs to the
<code>generate_workout</code> function</span></p>
<p>That's the context of what we're working on. The <code>generate_workout</code> function in
Listing 13-3 contains the business logic of the app that we're most concerned
with in this example. The rest of the code changes in this example will be made
to this function:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# use std::thread;
# use std::time::Duration;
#
# fn simulated_expensive_calculation(num: i32) -&gt; i32 {
#     println!(&quot;calculating slowly...&quot;);
#     thread::sleep(Duration::from_secs(2));
#     num
# }
#
fn generate_workout(intensity: i32, random_number: i32) {
    if intensity &lt; 25 {
        println!(
            &quot;Today, do {} pushups!&quot;,
            simulated_expensive_calculation(intensity)
        );
        println!(
            &quot;Next, do {} situps!&quot;,
            simulated_expensive_calculation(intensity)
        );
    } else {
        if random_number == 3 {
            println!(&quot;Take a break today! Remember to stay hydrated!&quot;);
        } else {
            println!(
                &quot;Today, run for {} minutes!&quot;,
                simulated_expensive_calculation(intensity)
            )
        }
    }
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-3: The business logic of the program that
prints the workout plans based on the inputs and calls to the
<code>simulated_expensive_calculation</code> function</span></p>
<p>The code in Listing 13-3 has multiple calls to the slow calculation function.
The first <code>if</code> block calls <code>simulated_expensive_calculation</code> twice, the <code>if</code>
inside the outer <code>else</code> doesn't call it at all, and the code inside the <code>else</code>
case inside the outer <code>else</code> calls it once.</p>
<!-- Will add wingdings in libreoffice /Carol -->
<p>The desired behavior of the <code>generate_workout</code> function is to first check if
the user wants a low intensity workout (indicated by a number less than 25) or
a high intensity workout (25 or more). Low intensity workout plans will
recommend a number of pushups and situps based on the complex algorithm we're
simulating with the <code>simulated_expensive_calculation</code> function, which needs the
intensity number as an input.</p>
<p>If the user wants a high intensity workout, there's some additional logic: if
the value of the random number generated by the app happens to be 3, the app
will recommend a break and hydration instead. If not, the user will get a high
intensity workout of a number of minutes of running that comes from the complex
algorithm.</p>
<p>The data science team has let us know that there are going to be some changes
to the way we have to call the algorithm, so we want to refactor this code to
have only one place that calls the <code>simulated_expensive_calculation</code> function
to update when those changes happen. We also want to get rid of the spot where
we're currently calling the function twice unnecessarily, and we don't want to
add any other calls to that function in the process. That is, we don't want to
call it if we're in the case where the result isn't needed at all, and we still
want to call it only once in the last case.</p>
<p>There are many ways we could restructure this program. The way we're going to
try first is extracting the duplicated call to the expensive calculation
function into a variable, as shown in Listing 13-4:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# use std::thread;
# use std::time::Duration;
#
# fn simulated_expensive_calculation(num: i32) -&gt; i32 {
#     println!(&quot;calculating slowly...&quot;);
#     thread::sleep(Duration::from_secs(2));
#     num
# }
#
fn generate_workout(intensity: i32, random_number: i32) {
    let expensive_result =
        simulated_expensive_calculation(intensity);

    if intensity &lt; 25 {
        println!(
            &quot;Today, do {} pushups!&quot;,
            expensive_result
        );
        println!(
            &quot;Next, do {} situps!&quot;,
            expensive_result
        );
    } else {
        if random_number == 3 {
            println!(&quot;Take a break today! Remember to stay hydrated!&quot;);
        } else {
            println!(
                &quot;Today, run for {} minutes!&quot;,
                expensive_result
            )
        }
    }
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-4: Extracting the calls to
<code>simulated_expensive_calculation</code> to one place before the <code>if</code> blocks and
storing the result in the <code>expensive_result</code> variable</span></p>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>This change unifies all the calls to <code>simulated_expensive_calculation</code> and
solves the problem of the first <code>if</code> block calling the function twice
unnecessarily. Unfortunately, we're now calling this function and waiting for
the result in all cases, which includes the inner <code>if</code> block that doesn't use
the result value at all.</p>
<p>We want to be able to specify some code in one place in our program, but then
only execute that code if we actually need the result in some other place in
our program. This is a use case for closures!</p>
<a class="header" href="ch13-01-closures.html#closures-store-code-to-be-executed-later" id="closures-store-code-to-be-executed-later"><h3>Closures Store Code to be Executed Later</h3></a>
<p>Instead of always calling the <code>simulated_expensive_calculation</code> function before
the <code>if</code> blocks, we can define a closure and store the closure in a variable
instead of the result as shown in Listing 13-5. We can actually choose to move
the whole body of <code>simulated_expensive_calculation</code> within the closure we're
introducing here:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# use std::thread;
# use std::time::Duration;
#
let expensive_closure = |num| {
    println!(&quot;calculating slowly...&quot;);
    thread::sleep(Duration::from_secs(2));
    num
};
# expensive_closure(5);

#}</code></pre></pre>
<p><span class="caption">Listing 13-5: Defining a closure with the body that was
in the expensive function and store the closure in the <code>expensive_closure</code>
variable</span></p>
<!-- Can you elaborate on *how* to define the closure first? I've had a go here
based on what I can see but not sure it's correct. Are we saying that a closure
is function that assigned its result to a variable you can then use? -->
<!-- I've attempted to elaborate on defining a closure in the next few
paragraphs starting here, is this better? /Carol -->
<p>The closure definition is the part after the <code>=</code> that we're assigning to the
variable <code>expensive_closure</code>. To define a closure, we start with a pair of
vertical pipes (<code>|</code>). Inside the pipes is where we specify the parameters to
the closure; this syntax was chosen because of its similarity to closure
definitions in Smalltalk and Ruby. This closure has one parameter named <code>num</code>;
if we had more than one parameter, we would separate them with commas, like
<code>|param1, param2|</code>.</p>
<p>After the parameters, we put curly braces that hold the body of the closure.
The curly braces are optional if the closure body only has one line. After the
curly braces, we need a semicolon to go with the <code>let</code> statement. The value
returned from the last line in the closure body (<code>num</code>), since that line
doesn't end in a semicolon, will be the value returned from the closure when
it's called, just like in function bodies.</p>
<p>Note that this <code>let</code> statement means <code>expensive_closure</code> contains the
<em>definition</em> of an anonymous function, not the <em>resulting value</em> of calling the
anonymous function. Recall the reason we're using a closure is because we want
to define the code to call at one point, store that code, and actually call it
at a later point; the code we want to call is now stored in <code>expensive_closure</code>.</p>
<p>Now that we have the closure defined, we can change the code in the <code>if</code> blocks
to call the closure in order to execute the code and get the resulting value.
Calling a closure looks very similar to calling a function; we specify the
variable name that holds the closure definition and follow it with parentheses
containing the argument values we want to use for that call as shown in Listing
13-6:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# use std::thread;
# use std::time::Duration;
#
fn generate_workout(intensity: i32, random_number: i32) {
    let expensive_closure = |num| {
        println!(&quot;calculating slowly...&quot;);
        thread::sleep(Duration::from_secs(2));
        num
    };

    if intensity &lt; 25 {
        println!(
            &quot;Today, do {} pushups!&quot;,
            expensive_closure(intensity)
        );
        println!(
            &quot;Next, do {} situps!&quot;,
            expensive_closure(intensity)
        );
    } else {
        if random_number == 3 {
            println!(&quot;Take a break today! Remember to stay hydrated!&quot;);
        } else {
            println!(
                &quot;Today, run for {} minutes!&quot;,
                expensive_closure(intensity)
            )
        }
    }
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-6: Calling the <code>expensive_closure</code> we've
defined</span></p>
<p>Now we've achieved the goal of unifying where the expensive calculation is
called to one place, and we're only executing that code where we need the
results. However, we've reintroduced one of the problems from Listing 13-3:
we're still calling the closure twice in the first <code>if</code> block, which will call
the expensive code twice and make the user wait twice as long as they need to.
We could fix this problem by creating a variable local to that <code>if</code> block to
hold the result of calling the closure, but there's another solution we can use
since we have a closure. We'll get back to that solution in a bit; let's first
talk about why there aren't type annotations in the closure definition and the
traits involved with closures.</p>
<a class="header" href="ch13-01-closures.html#closure-type-inference-and-annotation" id="closure-type-inference-and-annotation"><h3>Closure Type Inference and Annotation</h3></a>
<p>Closure are different than functions defined with the <code>fn</code> keyword in a few
ways. The first is that closures don't require you to annotate the types of the
parameters or the return value like <code>fn</code> functions do.</p>
<!-- I've suggested moving this next paragraph up from below, I found this
section difficult to follow with this next paragraph -->
<p>Type annotations are required on functions because they're are part of an
explicit interface exposed to your users. Defining this interface rigidly is
important for ensuring that everyone agrees on what types of values a function
uses and returns. Closures aren't used in an exposed interface like this,
though: they're stored in variables and used without naming them and exposing
them to be invoked by users of our library.</p>
<p>Additionally, closures are usually short and only relevant within a narrow
context rather than in any arbitrary scenario. Within these limited contexts,
the compiler is reliably able to infer the types of the parameters and return
type similarly to how it's able to infer the types of most variables. Being
forced to annotate the types in these small, anonymous functions would be
annoying and largely redundant with the information the compiler already has
available.</p>
<!--Can you expand above on what you mean by "stored in bindings and called
directly"? Do you mean stored in a variable? I'm struggling to visualize how
closures are used, and what the important difference is between them and
functions. I think a clearer definition of what they are, what they do, and
what they're used for at the start of the closures section would help clear
this up -->
<!-- Yes, sorry, in Rust terminology "binding" is mostly synonymous to
"variable", but when we started working on the book we decided to be consistent
and more like what people are used to by referring to the concept as "variable"
throughout, but we missed this spot. /Carol -->
<p>Like variables, we can choose to add type annotations if we want to increase
explicitness and clarity in exchange for being more verbose than is strictly
necessary; annotating the types for the closure we defined in Listing 13-4
would look like the definition shown here in Listing 13-7:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# use std::thread;
# use std::time::Duration;
#
let expensive_closure = |num: i32| -&gt; i32 {
    println!(&quot;calculating slowly...&quot;);
    thread::sleep(Duration::from_secs(2));
    num
};

#}</code></pre></pre>
<p><span class="caption">Listing 13-7: Adding optional type annotations of the
parameter and return value types in the closure</span></p>
<!-- Why might you want to, if you don't need to? In a particular situation? -->
<!-- I've added an explanation /Carol -->
<!-- Below -- Am I right in assuming the closures below are doing the same
thing as the functions? -->
<!-- Yes /Carol -->
<p>The syntax of closures and functions looks more similar with type annotations.
Here's a vertical comparison of the syntax for the definition of a function
that adds one to its parameter, and a closure that has the same behavior. We've
added some spaces here to line up the relevant parts). This illustrates how
closure syntax is similar to function syntax except for the use of pipes rather
than parentheses and the amount of syntax that is optional:</p>
<!-- Prod: can you align this as shown in the text? -->
<!-- I'm confused, does this note mean that production *won't* be aligning all
of our other code examples as shown in the text? That's concerning to me, we're
trying to illustrate idiomatic Rust style in all the code examples, so our
alignment is always intentional... /Carol -->
<pre><code class="language-rust ignore">fn  add_one_v1   (x: i32) -&gt; i32 { x + 1 }
let add_one_v2 = |x: i32| -&gt; i32 { x + 1 };
let add_one_v3 = |x|             { x + 1 };
let add_one_v4 = |x|               x + 1  ;
</code></pre>
<!-- Can you point out where we're looking at here, where the important
differences lie? -->
<!-- The importance isn't the difference but the similarity... I've tried to
clarify /Carol -->
<!-- Will add wingdings and ghosting in libreoffice /Carol -->
<p>The first line shows a function definition, and the second line shows a fully
annotated closure definition. The third line removes the type annotations from
the closure definition, and the fourth line removes the braces that are
optional since the closure body only has one line. These are all valid
definitions that will produce the same behavior when they're called.</p>
<!--Below--I'm not sure I'm following, is the i8 type being inferred? It seems
like we're annotating it. -->
<!-- The types in the function definitions are being inferred, but since Rust's
variable types for numbers defaults to `i32`, in order to illustrate our point
here we're forcing the type of the *variable* to be `i8` by annotating it in
the *variable* declaration. I've changed the example to hopefully be less
confusing and convey our point better. /Carol -->
<p>Closure definitions will have one concrete type inferred for each of their
parameters and for their return value. For instance, Listing 13-8 shows the
definition of a short closure that just returns the value it gets as a
parameter. This closure isn't very useful except for the purposes of this
example. Note that we haven't added any type annotations to the definition: if
we then try to call the closure twice, using a <code>String</code> as an argument the
first time and an <code>i32</code> the second time, we'll get an error:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">let example_closure = |x| x;

let s = example_closure(String::from(&quot;hello&quot;));
let n = example_closure(5);
</code></pre>
<p><span class="caption">Listing 13-8: Attempting to call a closure whose types
are inferred with two different types</span></p>
<p>The compiler gives us this error:</p>
<pre><code class="language-text">error[E0308]: mismatched types
 --&gt; src/main.rs
  |
  | let n = example_closure(5);
  |                         ^ expected struct `std::string::String`, found
  integral variable
  |
  = note: expected type `std::string::String`
             found type `{integer}`
</code></pre>
<!-- Will add wingdings in libreoffice /Carol -->
<p>The first time we call <code>example_closure</code> with the <code>String</code> value, the compiler
infers the type of <code>x</code> and the return type of the closure to be <code>String</code>. Those
types are then locked in to the closure in <code>example_closure</code>, and we get a type
error if we try to use a different type with the same closure.</p>
<a class="header" href="ch13-01-closures.html#using-closures-with-generic-parameters-and-the-fn-traits" id="using-closures-with-generic-parameters-and-the-fn-traits"><h3>Using Closures with Generic Parameters and the <code>Fn</code> Traits</h3></a>
<p>Returning to our workout generation app, in Listing 13-6 we left our code still
calling the expensive calculation closure more times than it needs to. In each
place throughout our code, if we need the results of the expensive closure more
than once, we could save the result in a variable for reuse and use the
variable instead of calling the closure again. This could be a lot of repeated
code saving the results in a variety of places.</p>
<p>However, because we have a closure for the expensive calculation, we have
another solution available to us. We can create a struct that will hold the
closure and the resulting value of calling the closure. The struct will only
execute the closure if we need the resulting value, and it will cache the
resulting value so that the rest of our code doesn't have to be responsible for
saving and reusing the result. You may know this pattern as <em>memoization</em> or
<em>lazy evaluation</em>.</p>
<p>In order to make a struct that holds a closure, we need to be able to specify
the type of the closure. Each closure instance has its own unique anonymous
type: that is, even if two closures have the same signature, their types are
still considered to be different. In order to define structs, enums, or
function parameters that use closures, we use generics and trait bounds like we
discussed in Chapter 10.</p>
<!-- So Fn is a trait built into the language, is that right? I wasn't sure if
it was just a placeholder here -->
<!-- Fn is provided by the standard library; I've clarified here. /Carol -->
<p>The <code>Fn</code> traits are provided by the standard library. All closures implement
one of the traits <code>Fn</code>, <code>FnMut</code>, or <code>FnOnce</code>. We'll discuss the difference
between these traits in the next section on capturing the environment; in this
example, we can use the <code>Fn</code> trait.</p>
<p>We add types to the <code>Fn</code> trait bound to represent the types of the parameters
and return values that the closures must have in order to match this trait
bound. In this case, our closure has a parameter of type <code>i32</code> and returns an
<code>i32</code>, so the trait bound we specify is <code>Fn(i32) -&gt; i32</code>.</p>
<p>Listing 13-9 shows the definition of the <code>Cacher</code> struct that holds a closure
and an optional result value:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
struct Cacher&lt;T&gt;
    where T: Fn(i32) -&gt; i32
{
    calculation: T,
    value: Option&lt;i32&gt;,
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-9: Defining a <code>Cacher</code> struct that holds a
closure in <code>calculation</code> and an optional result in <code>value</code></span></p>
<p>The <code>Cacher</code> struct has a <code>calculation</code> field of the generic type <code>T</code>. The
trait bounds on <code>T</code> specify that <code>T</code> is a closure by using the <code>Fn</code> trait. Any
closure we want to store in the <code>calculation</code> field of a <code>Cacher</code> instance must
have one <code>i32</code> parameter (specified within the parentheses after <code>Fn</code>) and must
return an <code>i32</code> (specified after the <code>-&gt;</code>).</p>
<p>The <code>value</code> field is of type <code>Option&lt;i32&gt;</code>. Before we execute the closure,
<code>value</code> will be <code>None</code>. If the code using a <code>Cacher</code> asks for the result of the
closure, we'll execute the closure at that time and store the result within a
<code>Some</code> variant in the <code>value</code> field. Then if the code asks for the result of
the closure again, instead of executing the closure again, we'll return the
result that we're holding in the <code>Some</code> variant.</p>
<p>The logic around the <code>value</code> field that we've just described is defined in
Listing 13-10:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# struct Cacher&lt;T&gt;
#     where T: Fn(i32) -&gt; i32
# {
#     calculation: T,
#     value: Option&lt;i32&gt;,
# }
#
impl&lt;T&gt; Cacher&lt;T&gt;
    where T: Fn(i32) -&gt; i32
{
    fn new(calculation: T) -&gt; Cacher&lt;T&gt; {
        Cacher {
            calculation,
            value: None,
        }
    }

    fn value(&amp;mut self, arg: i32) -&gt; i32 {
        match self.value {
            Some(v) =&gt; v,
            None =&gt; {
                let v = (self.calculation)(arg);
                self.value = Some(v);
                v
            },
        }
    }
}

#}</code></pre></pre>
<!-- Liz: the `new` function is using the "struct init shorthand" by just
saying `calculation` instead of `calculation: calculation`, since the parameter
matches the struct field name. This was recently added to stable Rust and we've
added an introduction of it in Chapter 5. Just adding an explanation here for
you in case you read this chapter before the changes we've made to Chapter 5!
/Carol -->
<p><span class="caption">Listing 13-10: Implementations on <code>Cacher</code> of an
associated function named <code>new</code> and a method named <code>value</code> that manage the
caching logic</span></p>
<p>The fields on the <code>Cacher</code> struct are private since we want <code>Cacher</code> to manage
their values rather than letting the calling code potentially change the values
in these fields directly. The <code>Cacher::new</code> function takes a generic parameter
<code>T</code>, which we've defined in the context of the <code>impl</code> block to have the same
trait bound as the <code>Cacher</code> struct. <code>Cacher::new</code> returns a <code>Cacher</code> instance
that holds the closure specified in the <code>calculation</code> field and a <code>None</code> value
in the <code>value</code> field, since we haven't executed the closure yet.</p>
<p>When the calling code wants the result of evaluating the closure, instead of
calling the closure directly, it will call the <code>value</code> method. This method
checks to see if we already have a resulting value in <code>self.value</code> in a <code>Some</code>;
if we do, it returns the value within the <code>Some</code> without executing the closure
again.</p>
<p>If <code>self.value</code> is <code>None</code>, we call the closure stored in <code>self.calculation</code>,
save the result in <code>self.value</code> for future use, and return the value as well.</p>
<p>Listing 13-11 shows how we can use this <code>Cacher</code> struct in the
<code>generate_workout</code> function from Listing 13-6:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# use std::thread;
# use std::time::Duration;
#
# struct Cacher&lt;T&gt;
#     where T: Fn(i32) -&gt; i32
# {
#     calculation: T,
#     value: Option&lt;i32&gt;,
# }
#
# impl&lt;T&gt; Cacher&lt;T&gt;
#     where T: Fn(i32) -&gt; i32
# {
#     fn new(calculation: T) -&gt; Cacher&lt;T&gt; {
#         Cacher {
#             calculation,
#             value: None,
#         }
#     }
#
#     fn value(&amp;mut self, arg: i32) -&gt; i32 {
#         match self.value {
#             Some(v) =&gt; v,
#             None =&gt; {
#                 let v = (self.calculation)(arg);
#                 self.value = Some(v);
#                 v
#             },
#         }
#     }
# }
#
fn generate_workout(intensity: i32, random_number: i32) {
    let mut expensive_result = Cacher::new(|num| {
        println!(&quot;calculating slowly...&quot;);
        thread::sleep(Duration::from_secs(2));
        num
    });

    if intensity &lt; 25 {
        println!(
            &quot;Today, do {} pushups!&quot;,
            expensive_result.value(intensity)
        );
        println!(
            &quot;Next, do {} situps!&quot;,
            expensive_result.value(intensity)
        );
    } else {
        if random_number == 3 {
            println!(&quot;Take a break today! Remember to stay hydrated!&quot;);
        } else {
            println!(
                &quot;Today, run for {} minutes!&quot;,
                expensive_result.value(intensity)
            )
        }
    }
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-11: Using <code>Cacher</code> in the <code>generate_workout</code>
function to abstract away the caching logic</span></p>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Instead of saving the closure in a variable directly, we save a new instance of
<code>Cacher</code> that holds the closure. Then, in each place we want the result, we
call the <code>value</code> method on the <code>Cacher</code> instance. We can call the <code>value</code>
method as many times as we want, or not call it at all, and the expensive
calculation will be run a maximum of once. Try running this program with the
<code>main</code> function from Listing 13-2, and change the values in the
<code>simulated_user_specified_value</code> and <code>simulated_random_number</code> variables to
verify that in all of the cases in the various <code>if</code> and <code>else</code> blocks,
<code>calculating slowly...</code> printed by the closure only shows up once and only when
needed.</p>
<p>The <code>Cacher</code> takes care of the logic necessary to ensure we aren't calling the
expensive calculation more than we need to be so that <code>generate_workout</code> can
focus on the business logic. Caching values is a more generally useful behavior
that we might want to use in other parts of our code with other closures as
well. However, there are a few problems with the current implementation of
<code>Cacher</code> that would make reusing it in different contexts difficult.</p>
<p>The first problem is a <code>Cacher</code> instance assumes it will always get the same
value for the parameter <code>arg</code> to the <code>value</code> method. That is, this test of
<code>Cacher</code> will fail:</p>
<pre><code class="language-rust ignore">#[test]
fn call_with_different_values() {
    let mut c = Cacher::new(|a| a);

    let v1 = c.value(1);
    let v2 = c.value(2);

    assert_eq!(v2, 2);
}
</code></pre>
<p>This test creates a new <code>Cacher</code> instance with a closure that returns the value
passed into it. We call the <code>value</code> method on this <code>Cacher</code> instance with
an <code>arg</code> value of 1 and then an <code>arg</code> value of 2, and we expect that the call
to <code>value</code> with the <code>arg</code> value of 2 returns 2.</p>
<p>Run this with the <code>Cacher</code> implementation from Listing 13-9 and Listing 13-10
and the test will fail on the <code>assert_eq!</code> with this message:</p>
<pre><code class="language-text">thread 'call_with_different_arg_values' panicked at 'assertion failed:
`(left == right)` (left: `1`, right: `2`)', src/main.rs
</code></pre>
<p>The problem is that the first time we called <code>c.value</code> with 1, the <code>Cacher</code>
instance saved <code>Some(1)</code> in <code>self.value</code>. After that, no matter what we pass
in to the <code>value</code> method, it will always return 1.</p>
<p>Try modifying <code>Cacher</code> to hold a hash map rather than a single value. The keys
of the hash map will be the <code>arg</code> values that are passed in, and the values of
the hash map will be the result of calling the closure on that key. Instead of
looking at whether <code>self.value</code> directly has a <code>Some</code> or a <code>None</code> value, the
<code>value</code> function will look up the <code>arg</code> in the hash map and return the value if
it's present. If it's not present, the <code>Cacher</code> will call the closure and save
the resulting value in the hash map associated with its <code>arg</code> value.</p>
<p>Another problem with the current <code>Cacher</code> implementation that restricts its use
is that it only accepts closures that take one parameter of type <code>i32</code> and
return an <code>i32</code>. We might want to be able to cache the results of closures that
take a string slice as an argument and return <code>usize</code> values, for example. Try
introducing more generic parameters to increase the flexibility of the <code>Cacher</code>
functionality.</p>
<a class="header" href="ch13-01-closures.html#closures-can-capture-their-environment" id="closures-can-capture-their-environment"><h3>Closures Can Capture Their Environment</h3></a>
<p>In the workout generator example, we only used closures as inline anonymous
functions. Closures have an additional ability we can use that functions don't
have, however: they can capture their environment and access variables from the
scope in which they're defined.</p>
<!-- To clarify, by enclosing scope, do you mean the scope that the closure is
inside? Can you expand on that?-->
<!-- Yes, I've tried here to clarify that it's the scope in which the closure
is defined /Carol -->
<p>Listing 13-12 has an example of a closure stored in the variable <code>equal_to_x</code>
that uses the variable <code>x</code> from the closure's surrounding environment:</p>
<!-- To clarify how we talk about a closure, does the closure include the
variable name, or are we referring to the closure as the functionality that is
on the right side of the = and so not including to variable name? I thought it
was the former, but it seems like the latter above. If it's the former, would
"an example of a closure with the variable `equal_to_x`" make more sense? -->
<!-- No, the closure does not include the variable name in which it's stored;
storing a closure in a variable is optional. It should always be the latter,
and I hope the reworking of the example used throughout the closure section
and making the wording consistent has cleared this confusion up by this point.
/Carol -->
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust">fn main() {
    let x = 4;

    let equal_to_x = |z| z == x;

    let y = 4;

    assert!(equal_to_x(y));
}
</code></pre></pre>
<p><span class="caption">Listing 13-12: Example of a closure that refers to a
variable in its enclosing scope</span></p>
<p>Here, even though <code>x</code> is not one of the parameters of <code>equal_to_x</code>, the
<code>equal_to_x</code> closure is allowed to use the <code>x</code> variable that's defined in the
same scope that <code>equal_to_x</code> is defined in.</p>
<!-- So *why* is this allowed with closures and not functions, what about
closures makes this safe? -->
<!-- It's not really about safety; capturing the environment is the defining
functionality a closure has. The reason functions *don't* capture their
environment is mostly around storage overhead; I've added an explanation of
that aspect. Can you elaborate on what led to the conclusion that allowing
captures with functions wouldn't be safe and what you mean by "safe" here?
/Carol -->
<p>We can't do the same with functions; let's see what happens if we try:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">fn main() {
    let x = 4;

    fn equal_to_x(z: i32) -&gt; bool { z == x }

    let y = 4;

    assert!(equal_to_x(y));
}
</code></pre>
<p>We get an error:</p>
<pre><code class="language-text">error[E0434]: can't capture dynamic environment in a fn item; use the || { ... }
closure form instead
 --&gt;
  |
4 |     fn equal_to_x(z: i32) -&gt; bool { z == x }
  |                                          ^
</code></pre>
<p>The compiler even reminds us that this only works with closures!</p>
<p>When a closure captures a value from its environment, the closure uses memory
to store the values for use in the closure body. This use of memory is overhead
that we don't want pay for in the more common case where we want to execute
code that doesn't capture its environment. Because functions are never allowed
to capture their environment, defining and using functions will never incur
this overhead.</p>
<!-- Why didn't this work, is there a reason ingrained in the language? Or is
that not really relevant? -->
<!-- I've added an explanation /Carol -->
<p>Closures can capture values from their environment in three ways, which
directly map to the three ways a function can take a parameter: taking
ownership, borrowing immutably, and borrowing mutably. These ways of capturing
values are encoded in the three <code>Fn</code> traits as follows:</p>
<ul>
<li><code>FnOnce</code> takes ownership of the variables it captures from the environment
and moves those variables into the closure when the closure is defined.
Therefore, a <code>FnOnce</code> closure cannot be called more than once in the same
context.</li>
<li><code>Fn</code> borrows values from the environment immutably.</li>
<li><code>FnMut</code> can change the environment since it mutably borrows values.</li>
</ul>
<p>When we create a closure, Rust infers how we want to reference the environment
based on how the closure uses the values from the environment. In Listing
13-12, the <code>equal_to_x</code> closure borrows <code>x</code> immutably (so <code>equal_to_x</code> has the
<code>Fn</code> trait) since the body of the closure only needs to read the value in <code>x</code>.</p>
<p>If we want to force the closure to take ownership of the values it uses in the
environment, we can use the <code>move</code> keyword before the parameter list. This is
mostly useful when passing a closure to a new thread in order to move the data
to be owned by the new thread. We'll have more examples of <code>move</code> closures in
Chapter 16 when we talk about concurrency, but for now here's the code from
Listing 13-12 with the <code>move</code> keyword added to the closure definition and using
vectors instead of integers, since integers can be copied rather than moved:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">fn main() {
    let x = vec![1, 2, 3];

    let equal_to_x = move |z| z == x;

    println!(&quot;can't use x here: {:?}&quot;, x);

    let y = vec![1, 2, 3];

    assert!(equal_to_x(y));
}
</code></pre>
<p>This example doesn't compile:</p>
<pre><code class="language-text">error[E0382]: use of moved value: `x`
 --&gt; src/main.rs:6:40
  |
4 |     let equal_to_x = move |z| z == x;
  |                      -------- value moved (into closure) here
5 |
6 |     println!(&quot;can't use x here: {:?}&quot;, x);
  |                                        ^ value used here after move
  |
  = note: move occurs because `x` has type `std::vec::Vec&lt;i32&gt;`, which does not
    implement the `Copy` trait
</code></pre>
<p>The <code>x</code> value is moved into the closure when the closure is defined because of
the <code>move</code> keyword. The closure then has ownership of <code>x</code>, and <code>main</code> isn't
allowed to use <code>x</code> anymore. Removing the <code>println!</code> will fix this example.</p>
<p>Most of the time when specifying one of the <code>Fn</code> trait bounds, you can start
with <code>Fn</code> and the compiler will tell you if you need <code>FnMut</code> or <code>FnOnce</code> based
on what happens in the closure body.</p>
<p>To illustrate situations where closures that can capture their environment are
useful as function parameters, let's move on to our next topic: iterators.</p>

                </div>

                <!-- Mobile navigation buttons -->
                
                    <a href="ch13-00-functional-features.html" class="mobile-nav-chapters previous">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="ch13-02-iterators.html" class="mobile-nav-chapters next">
                        <i class="fa fa-angle-right"></i>
                    </a>
                

            </div>

            
                <a href="ch13-00-functional-features.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-left"></i>
                </a>
            

            
                <a href="ch13-02-iterators.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-right"></i>
                </a>
            

        </div>


        <!-- Local fallback for Font Awesome -->
        <script>
            if ($(".fa").css("font-family") !== "FontAwesome") {
                $('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
            }
        </script>

        <!-- Livereload script (if served using the cli tool) -->
        

        <script src="highlight.js"></script>
        <script src="book.js"></script>
    </body>
</html>