Sophie

Sophie

distrib > Mageia > 6 > armv7hl > media > core-updates > by-pkgid > 564935689ab5527f955e5449ded02799 > files > 276

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

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Iterators - 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"><strong>13.1.</strong> Closures</a></li><li><a href="ch13-02-iterators.html" class="active"><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-02-iterators.html#processing-a-series-of-items-with-iterators" id="processing-a-series-of-items-with-iterators"><h2>Processing a Series of Items with Iterators</h2></a>
<!-- From reading on, it seems like an iterator is useless without the methods
we use it with --- I think this is an important point to make early, I did find
it difficult to know what an iterator actually was throughout, and how it
depends on these other methods. Can you add something to this effect? -->
<!-- Reiterating the need for a clear definition of an iterator here--it seems
like an item that's used in iteration rather than something that performs the
process of iteration itself, is that right? Like a counter passed from element
to element? Can we define this at the begin of the iterator section? -->
<!-- I've added an explanation along these lines, does this help? /Carol -->
<p>The iterator pattern allows you to perform some task on a sequence of items in
turn. An <em>iterator</em> is responsible for the logic around iterating over each item
in the sequence and determining when the sequence has finished. When we use
iterators, we don't have to reimplement that logic ourselves.</p>
<p>In Rust, iterators are <em>lazy</em>, which means they have no effect until we call
methods on them that consume the iterator to use it up. For example, the code
in Listing 13-13 creates an iterator over the items in the vector <code>v1</code> by
calling the <code>iter</code> method defined on <code>Vec</code>. This code by itself doesn't do
anything useful:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
let v1 = vec![1, 2, 3];

let v1_iter = v1.iter();

#}</code></pre></pre>
<p><span class="caption">Listing 13-13: Creating an iterator; this by itself isn't
useful</span></p>
<p>After creating an iterator, we can choose to use it in a variety of ways. In
Listing 3-6, we actually used iterators with <code>for</code> loops to execute some code
on each item, though we glossed over what the call to <code>iter</code> did until now. The
example in Listing 13-14 separates the creation of the iterator from the use of
the iterator in the <code>for</code> loop. The iterator is stored in the <code>v1_iter</code>
variable, and no iteration takes place at that time. Once the <code>for</code> loop is
called using the iterator in <code>v1_iter</code>, then each element in the iterator is
used in one iteration of the loop, which prints out each value:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
let v1 = vec![1, 2, 3];

let v1_iter = v1.iter();

for val in v1_iter {
    println!(&quot;Got: {}&quot;, val);
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-13: Making use of an iterator in a <code>for</code>
loop</span></p>
<p>In languages that don't have iterators provided by their standard libraries, we
would likely write this same functionality by starting a variable at index 0,
using that variable to index into the vector to get a value, and incrementing
the variable value in a loop until its value gets up to the total number of
items in the vector. Iterators take care of all of that logic for us, which
cuts down on the repetitive code we would have to write and potentially mess up.
In addition, the way iterators are implemented gives us more flexibility to
use the same logic with many different kinds of sequences, not just data
structures that we can index into like vectors. Let's see how iterators do that.</p>
<a class="header" href="ch13-02-iterators.html#the-iterator-trait-and-the-next-method" id="the-iterator-trait-and-the-next-method"><h3>The <code>Iterator</code> trait and the <code>next</code> method</h3></a>
<p>Iterators all implement a trait named <code>Iterator</code> that is defined in the
standard library. The definition of the trait looks like this:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
trait Iterator {
    type Item;

    fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt;;

    // methods with default implementations elided
}

#}</code></pre></pre>
<p>You'll notice some new syntax that we haven't covered yet: <code>type Item</code> and
<code>Self::Item</code>, which are defining an <em>associated type</em> with this trait. We'll
talk about associated types in depth in Chapter 19, but for now, all you need
to know is that this code says implementing <code>Iterator</code> trait requires that you
also define an <code>Item</code> type, and this <code>Item</code> type is used in the return type of
the <code>next</code> method. In other words, the <code>Item</code> type will be the type of element
that's returned from the iterator.</p>
<p>The <code>next</code> method is the only method that the <code>Iterator</code> trait requires
implementers of the trait to define. <code>next</code> returns one item of the iterator
at a time wrapped in <code>Some</code>, and when iteration is over, it returns <code>None</code>.
We can call the <code>next</code> method on iterators directly if we'd like; Listing 13-14
has a test that demonstrates the values we'd get on repeated calls to <code>next</code>
on the iterator created from the vector:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust test_harness"># #![allow(unused_variables)]
#fn main() {
#[test]
fn iterator_demonstration() {
    let v1 = vec![1, 2, 3];

    let mut v1_iter = v1.iter();

    assert_eq!(v1_iter.next(), Some(&amp;1));
    assert_eq!(v1_iter.next(), Some(&amp;2));
    assert_eq!(v1_iter.next(), Some(&amp;3));
    assert_eq!(v1_iter.next(), None);
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-14: Calling the <code>next</code> method on an
iterator</span></p>
<p>Note that we needed to make <code>v1_iter</code> mutable: calling the <code>next</code> method on an
iterator changes the iterator's state that keeps track of where it is in the
sequence. Put another way, this code <em>consumes</em>, or uses up, the iterator. Each
call to <code>next</code> eats up an item from the iterator.</p>
<p>Also note that the values we get from the calls to <code>next</code> are immutable
references to the values in the vector. The <code>iter</code> method produces an iterator
over immutable references. If we wanted to create an iterator that takes
ownership of <code>v1</code> and returns owned values, we can call <code>into_iter</code> instead of
<code>iter</code>. Similarly, if we want to iterate over mutable references, we can call
<code>iter_mut</code> instead of <code>iter</code>.</p>
<a class="header" href="ch13-02-iterators.html#methods-in-the-iterator-trait-that-consume-the-iterator" id="methods-in-the-iterator-trait-that-consume-the-iterator"><h3>Methods in the <code>Iterator</code> Trait that Consume the Iterator</h3></a>
<!-- Can you explain what it is you mean by "consumes" an iterator here? It
doesn't look like we do in this section, I think that's important to lay that
out clearly -->
<!-- This next paragraph doesn't give much away to me I'm afraid, not being
clear what we mean by *consume* at this point. Is a consuming adaptor like a
catalyst? -->
<!-- I hope this section addresses these comments you had /Carol -->
<p>The <code>Iterator</code> trait has a number of different methods with default
implementations provided for us by the standard library; you can find out all
about these methods by looking in the standard library API documentation for
the <code>Iterator</code> trait. Some of these methods call the <code>next</code> method in their
definition, which is why we're required to implement the <code>next</code> method when
implementing the <code>Iterator</code> trait.</p>
<!-- Is there somewhere they can learn about all the methods and what they do,
how to use them? This seems like a good sample example, and if we can broaden
it out that would be really helpful -->
<!-- I've moved this comment here since you made this comment on the last
version of this chapter right after a spot where we mentioned looking at the
standard library API documentation for the iterator trait, like we're now doing
in the above paragraph. That's where the reader should go to learn about
all the methods and what they do and how to use them. Can you elaborate on why
that wasn't clear in the previous version of the chapter? Is there a reason why
the standard library API documentation didn't sound like that place to go?
/Carol -->
<p>The methods that call the <code>next</code> method are called <em>consuming adaptors</em>, since
calling them uses up the iterator. An example of a consuming adaptor is the
<code>sum</code> method. This method takes ownership of the iterator and iterates through
the items by repeatedly calling <code>next</code>, thus consuming the iterator. As it
iterates through each item, it adds each item to a running total and returns
the total when iteration has completed. Listing 13-15 has a test illustrating a
use of the <code>sum</code> method:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
#[test]
fn iterator_sum() {
    let v1 = vec![1, 2, 3];

    let v1_iter = v1.iter();

    let total: i32 = v1_iter.sum();

    assert_eq!(total, 6);
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-15: Calling the <code>sum</code> method to get the total
of all items in the iterator</span></p>
<p>We aren't allowed to use <code>v1_iter</code> after the call to <code>sum</code> since <code>sum</code> takes
ownership of the iterator we call it on.</p>
<a class="header" href="ch13-02-iterators.html#methods-in-the-iterator-trait-that-produce-other-iterators" id="methods-in-the-iterator-trait-that-produce-other-iterators"><h3>Methods in the <code>Iterator</code> Trait that Produce Other Iterators</h3></a>
<p>Another kind of method defined on the <code>Iterator</code> trait are methods that produce
other iterators. These methods are called <em>iterator adaptors</em> and allow us to
change iterators into different kind of iterators. We can chain multiple calls
to iterator adaptors. Because all iterators are lazy, however, we have to
call one of the consuming adaptor methods in order to get results from calls
to iterator adaptors. Listing 13-16 shows an example of calling the iterator
adaptor method <code>map</code>, which takes a closure that <code>map</code> will call on each
item in order to produce a new iterator in which each item from the vector has
been incremented by 1. This code produces a warning, though:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
let v1: Vec&lt;i32&gt; = vec![1, 2, 3];

v1.iter().map(|x| x + 1);

#}</code></pre></pre>
<p><span class="caption">Listing 13-16: Calling the iterator adapter <code>map</code> to
create a new iterator</span></p>
<p>The warning we get is:</p>
<pre><code class="language-text">warning: unused result which must be used: iterator adaptors are lazy and do
nothing unless consumed
 --&gt; src/main.rs:4:1
  |
4 | v1.iter().map(|x| x + 1);
  | ^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(unused_must_use)] on by default
</code></pre>
<p>The code in Listing 13-16 isn't actually doing anything; the closure we've
specified never gets called. The warning reminds us why: iterator adaptors are
lazy, and we probably meant to consume the iterator here.</p>
<p>In order to fix this warning and consume the iterator to get a useful result,
we're going to use the <code>collect</code> method, which we saw briefly in Chapter 12.
This method consumes the iterator and collects the resulting values into a
data structure. In Listing 13-17, we're going to collect the results of
iterating over the iterator returned from the call to <code>map</code> into a vector that
will contain each item from the original vector incremented by 1:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
let v1: Vec&lt;i32&gt; = vec![1, 2, 3];

let v2: Vec&lt;_&gt; = v1.iter().map(|x| x + 1).collect();

assert_eq!(v2, vec![2, 3, 4]);

#}</code></pre></pre>
<p><span class="caption">Listing 13-17: Calling the <code>map</code> method to create a new
iterator, then calling the <code>collect</code> method to consume the new iterator and
create a vector</span></p>
<p>Because <code>map</code> takes a closure, we can specify any operation that we want to
perform on each item that we iterate over. This is a great example of how using
closures lets us customize some behavior while reusing the iteration behavior
that the <code>Iterator</code> trait provides.</p>
<!-- I'm not clear from this last sentence which part is iterating through each
element, iter or map? What is map actually doing?-->
<!--Ah, I'm afraid I completely failed to follow this. What is the second
iterator for? I'm still not clear on what map does, can you expand on this? It
seems crucial to using iterators. Map applies the iterator to each element,
which applies the closure?
<p>Also, to generalize this discussion a bit, would you ever use iter without map?
--&gt;</p>
<!-- I hope this new breakdown/rearranging has cleared up these comments you
had on the last version of this chapter about the difference between
iter and map. I hope the added examples where we've used iter without map have
cleared up the last question. /Carol -->
<a class="header" href="ch13-02-iterators.html#using-closures-that-capture-their-environment-with-iterators" id="using-closures-that-capture-their-environment-with-iterators"><h3>Using Closures that Capture their Environment with Iterators</h3></a>
<p>Now that we've introduced iterators, we can demonstrate a common use of
closures that capture their environment by using the <code>filter</code> iterator adapter.
The <code>filter</code> method on an iterator takes a closure that takes each item from
the iterator and returns a boolean. If the closure returns <code>true</code>, the value
will be included in the iterator produced by <code>filter</code>. If the closure returns
<code>false</code>, the value won't be included in the resulting iterator. Listing 13-18
demonstrates using <code>filter</code> with a closure that captures the <code>shoe_size</code>
variable from its environment in order to iterate over a collection of <code>Shoe</code>
struct instances in order to return only shoes that are the specified size:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust test_harness"># #![allow(unused_variables)]
#fn main() {
#[derive(PartialEq, Debug)]
struct Shoe {
    size: i32,
    style: String,
}

fn shoes_in_my_size(shoes: Vec&lt;Shoe&gt;, shoe_size: i32) -&gt; Vec&lt;Shoe&gt; {
    shoes.into_iter()
        .filter(|s| s.size == shoe_size)
        .collect()
}

#[test]
fn filters_by_size() {
    let shoes = vec![
        Shoe { size: 10, style: String::from(&quot;sneaker&quot;) },
        Shoe { size: 13, style: String::from(&quot;sandal&quot;) },
        Shoe { size: 10, style: String::from(&quot;boot&quot;) },
    ];

    let in_my_size = shoes_in_my_size(shoes, 10);

    assert_eq!(
        in_my_size,
        vec![
            Shoe { size: 10, style: String::from(&quot;sneaker&quot;) },
            Shoe { size: 10, style: String::from(&quot;boot&quot;) },
        ]
    );
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-18: Using the <code>filter</code> method with a closure
that captures <code>shoe_size</code></span></p>
<!-- Will add wingdings in libreoffice /Carol -->
<p>The <code>shoes_in_my_size</code> function takes ownership of a vector of shoes and a shoe
size as parameters. It returns a vector containing only shoes of the specified
size. In the body of <code>shoes_in_my_size</code>, we call <code>into_iter</code> to create an
iterator that takes ownership of the vector. Then we call <code>filter</code> to adapt
that iterator into a new iterator that only contains elements for which the
closure returns <code>true</code>. The closure we've specified captures the <code>shoe_size</code>
parameter from the environment and uses the value to compare with each shoe's
size to only keep shoes that are of the size specified. Finally, calling
<code>collect</code> gathers the values returned by the adapted iterator into a vector
that the function returns.</p>
<p>The test shows that when we call <code>shoes_in_my_size</code>, we only get back shoes
that have the same size as the value we specified.</p>
<a class="header" href="ch13-02-iterators.html#implementing-the-iterator-trait-to-create-our-own-iterators" id="implementing-the-iterator-trait-to-create-our-own-iterators"><h3>Implementing the <code>Iterator</code> Trait to Create Our Own Iterators</h3></a>
<!-- So it seems like we are creating a program with an iterator inside, is
that right? I assumed the whole thing we were making was an iterator at first,
which lead to a few confusions, can you lay it out up front? -->
<!-- I'm not sure what you mean here, can you elaborate on what the distinction
is to you between "a program with an iterator inside" and "whole thing we were
making was an iterator"? I don't understand what you mean by these terms so I'm
not sure how to clear this up. /Carol -->
<p>We've shown that we can create an iterator by calling <code>iter</code>, <code>into_iter</code>, or
<code>iter_mut</code> on a vector. We can also create iterators from the other collection
types in the standard library, such as hash map. Additionally, we can implement
the <code>Iterator</code> trait in order to create iterators that do anything we want.
As previously mentioned, the only method we're required to provide a definition
for is the <code>next</code> method. Once we've done that, we can use all the other
methods that have default implementations provided by the <code>Iterator</code> trait on
our iterator!</p>
<!-- NEXT PARAGRAPH WRAPPED WEIRD INTENTIONALLY SEE #199 -->
<p>The iterator we're going to create is one that will only ever count from 1
to 5. First, we'll create a struct to hold on to some values, and then we'll
make this struct into an iterator by implementing the <code>Iterator</code> trait and use
the values in that implementation.</p>
<p>Listing 13-19 has the definition of the <code>Counter</code> struct and an associated
<code>new</code> function to create instances of <code>Counter</code>:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
struct Counter {
    count: u32,
}

impl Counter {
    fn new() -&gt; Counter {
        Counter { count: 0 }
    }
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-19: Defining the <code>Counter</code> struct and a <code>new</code>
function that creates instances of <code>Counter</code> with an initial value of 0 for
<code>count</code></span></p>
<!-- Could you add a filename here? I think that will help the reader keep
track of what they're working on. Can you also just sum up in a line what this
code has accomplished so far? I moved this down from above the code, if this
will do? -->
<!-- Done /Carol -->
<p>The <code>Counter</code> struct has one field named <code>count</code>. This field holds a <code>u32</code>
value that will keep track of where we are in the process of iterating from 1
to 5. The <code>count</code> field is private since we want the implementation of
<code>Counter</code> to manage its value. The <code>new</code> function enforces the behavior we want
of always starting new instances with a value of 0 in the <code>count</code> field.</p>
<!-- Why define the new method, if it isn't necessary? Or is that what this
next line is telling us? -->
<!-- So does this code just initialize it with 0? Is that jat { count: 0 }
does?-->
<!-- I've rearranged to make this clearer /Carol -->
<p>Next, we're going to implement the <code>Iterator</code> trait for our <code>Counter</code> type by
defining the body of the <code>next</code> method to specify what we want to happen when
this iterator is used, as shown in Listing 13-20:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# struct Counter {
#     count: u32,
# }
#
impl Iterator for Counter {
    type Item = u32;

    fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
        self.count += 1;

        if self.count &lt; 6 {
            Some(self.count)
        } else {
            None
        }
    }
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-20: Implementing the <code>Iterator</code> trait on our
<code>Counter</code> struct</span></p>
<!-- I will add wingdings in libreoffice /Carol -->
<p>We set the associated <code>Item</code> type for our iterator to <code>u32</code>, meaning the
iterator will return <code>u32</code> values. Again, don't worry about associated types
yet, we'll be covering them in Chapter 19. We want our iterator to add one to
the current state, which is why we initialized <code>count</code> to 0: we want our
iterator to return one first. If the value of <code>count</code> is less than six, <code>next</code>
will return the current value wrapped in <code>Some</code>, but if <code>count</code> is six or
higher, our iterator will return <code>None</code>.</p>
<a class="header" href="ch13-02-iterators.html#using-our-counter-iterators-next-method" id="using-our-counter-iterators-next-method"><h4>Using Our <code>Counter</code> Iterator's <code>next</code> Method</h4></a>
<p>Once we've implemented the <code>Iterator</code> trait, we have an iterator! Listing 13-21
shows a test demonstrating that we can use the iterator functionality our
<code>Counter</code> struct now has by calling the <code>next</code> method on it directly, just like
we did with the iterator created from a vector in Listing 13-14:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# struct Counter {
#     count: u32,
# }
#
# impl Iterator for Counter {
#     type Item = u32;
#
#     fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
#         self.count += 1;
#
#         if self.count &lt; 6 {
#             Some(self.count)
#         } else {
#             None
#         }
#     }
# }
#
#[test]
fn calling_next_directly() {
    let mut counter = Counter::new();

    assert_eq!(counter.next(), Some(1));
    assert_eq!(counter.next(), Some(2));
    assert_eq!(counter.next(), Some(3));
    assert_eq!(counter.next(), Some(4));
    assert_eq!(counter.next(), Some(5));
    assert_eq!(counter.next(), None);
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-21: Testing the functionality of the <code>next</code>
method implementation</span></p>
<p>This test creates a new <code>Counter</code> instance in the <code>counter</code> variable and then
calls <code>next</code> repeatedly, verifying that we have implemented the behavior we
want this iterator to have of returning the values from 1 to 5.</p>
<!-- So if I have this right, the first line creates a new Counter called
counter, and the rest of them merely call counter with next, store it in x, and
then print x? And we have to do that 5 times to get the 1-5 count? Phew, could
you wrap that up if indeed it is correct!) and sum up here? -->
<!-- I decided to change this into a test rather than printing out values, and
I added some summary text about what the test is doing. Is this clearer? /Carol
-->
<a class="header" href="ch13-02-iterators.html#using-other-iterator-trait-methods-on-our-iterator" id="using-other-iterator-trait-methods-on-our-iterator"><h4>Using Other <code>Iterator</code> Trait Methods on Our Iterator</h4></a>
<p>Because we implemented the <code>Iterator</code> trait by defining the <code>next</code> method, we
can now use any <code>Iterator</code> trait method's default implementations that the
standard library has defined, since they all use the <code>next</code> method's
functionality.</p>
<!-- So we can't just use these methods anyway? It seems like we did earlier,
but here we have to use next first, before we cam access these methods? -->
<!-- No, we don't have to *use* `next` before we can use the other methods, we
have to *define* `next` before we can use the other methods. I hope the various
rewordings and reworkings have made this clearer by this point. /Carol -->
<!-- below: once you've done what, defined a default implementation? Only then
can you use other adapters, is that what we're saying? And I'm still not clear
on what an adapter does/means, as opposed to a method, or consumer, at this
point. -->
<!-- I hope this comment has been cleared up too /Carol -->
<p>For example, if for some reason we wanted to take the values that an instance
of <code>Counter</code> produces, pair those values with values produced by another
<code>Counter</code> instance after skipping the first value that instance produces,
multiply each pair together, keep only those results that are divisible by
three, and add all the resulting values together, we could do so as shown in
the test in Listing 13-22:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# struct Counter {
#     count: u32,
# }
#
# impl Counter {
#     fn new() -&gt; Counter {
#         Counter { count: 0 }
#     }
# }
#
# impl Iterator for Counter {
#     // Our iterator will produce u32s
#     type Item = u32;
#
#     fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
#         // increment our count. This is why we started at zero.
#         self.count += 1;
#
#         // check to see if we've finished counting or not.
#         if self.count &lt; 6 {
#             Some(self.count)
#         } else {
#             None
#         }
#     }
# }
#
#[test]
fn using_other_iterator_trait_methods() {
    let sum: u32 = Counter::new().zip(Counter::new().skip(1))
                                 .map(|(a, b)| a * b)
                                 .filter(|x| x % 3 == 0)
                                 .sum();
    assert_eq!(18, sum);
}

#}</code></pre></pre>
<p><span class="caption">Listing 13-22: Using a variety of <code>Iterator</code> trait
methods on our <code>Counter</code> iterator</span></p>
<p>Note that <code>zip</code> produces only four pairs; the theoretical fifth pair <code>(5, None)</code> is never produced because <code>zip</code> returns <code>None</code> when either of its input
iterators return <code>None</code>.</p>
<p>All of these method calls are possible because we implemented the <code>Iterator</code>
trait by specifying how the <code>next</code> method works and the standard library
provides default implementations for other methods that call <code>next</code>.</p>

                </div>

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

                
                    <a href="ch13-03-improving-our-io-project.html" class="mobile-nav-chapters next">
                        <i class="fa fa-angle-right"></i>
                    </a>
                

            </div>

            
                <a href="ch13-01-closures.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-03-improving-our-io-project.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>