Sophie

Sophie

distrib > Mageia > 6 > x86_64 > media > core-updates > by-pkgid > fdedb3cf2140df9b6d419a2338ab1caa > files > 497

rust-doc-1.25.0-1.mga6.x86_64.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">
        <meta name="theme-color" content="#ffffff" />

        <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 href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" 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">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme -->
        

        

        <!-- Fetch Clipboard.js from CDN but have a local fallback -->
        <script src="https://cdn.jsdelivr.net/clipboard.js/1.6.1/clipboard.min.js"></script>
        <script>
            if (typeof Clipboard == 'undefined') {
                document.write(unescape("%3Cscript src='clipboard.min.js'%3E%3C/script%3E"));
            }
        </script>

    </head>
    <body class="light">
        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } 
            if (theme === null || theme === undefined) { theme = 'light'; }
            document.body.className = theme;
            document.querySelector('html').className = theme;
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            document.querySelector('html').classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <ol class="chapter"><li class="affix"><a href="README.html">Introduction</a></li><li><a href="getting-started.html"><strong aria-hidden="true">1.</strong> Getting Started</a></li><li><a href="guessing-game.html"><strong aria-hidden="true">2.</strong> Tutorial: Guessing Game</a></li><li><a href="syntax-and-semantics.html"><strong aria-hidden="true">3.</strong> Syntax and Semantics</a></li><li><ol class="section"><li><a href="variable-bindings.html"><strong aria-hidden="true">3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong aria-hidden="true">3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong aria-hidden="true">3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong aria-hidden="true">3.4.</strong> Comments</a></li><li><a href="if.html"><strong aria-hidden="true">3.5.</strong> if</a></li><li><a href="loops.html"><strong aria-hidden="true">3.6.</strong> Loops</a></li><li><a href="vectors.html"><strong aria-hidden="true">3.7.</strong> Vectors</a></li><li><a href="ownership.html"><strong aria-hidden="true">3.8.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong aria-hidden="true">3.9.</strong> References and Borrowing</a></li><li><a href="lifetimes.html"><strong aria-hidden="true">3.10.</strong> Lifetimes</a></li><li><a href="mutability.html"><strong aria-hidden="true">3.11.</strong> Mutability</a></li><li><a href="structs.html"><strong aria-hidden="true">3.12.</strong> Structs</a></li><li><a href="enums.html"><strong aria-hidden="true">3.13.</strong> Enums</a></li><li><a href="match.html"><strong aria-hidden="true">3.14.</strong> Match</a></li><li><a href="patterns.html"><strong aria-hidden="true">3.15.</strong> Patterns</a></li><li><a href="method-syntax.html"><strong aria-hidden="true">3.16.</strong> Method Syntax</a></li><li><a href="strings.html"><strong aria-hidden="true">3.17.</strong> Strings</a></li><li><a href="generics.html"><strong aria-hidden="true">3.18.</strong> Generics</a></li><li><a href="traits.html"><strong aria-hidden="true">3.19.</strong> Traits</a></li><li><a href="drop.html"><strong aria-hidden="true">3.20.</strong> Drop</a></li><li><a href="if-let.html"><strong aria-hidden="true">3.21.</strong> if let</a></li><li><a href="trait-objects.html"><strong aria-hidden="true">3.22.</strong> Trait Objects</a></li><li><a href="closures.html"><strong aria-hidden="true">3.23.</strong> Closures</a></li><li><a href="ufcs.html"><strong aria-hidden="true">3.24.</strong> Universal Function Call Syntax</a></li><li><a href="crates-and-modules.html"><strong aria-hidden="true">3.25.</strong> Crates and Modules</a></li><li><a href="const-and-static.html"><strong aria-hidden="true">3.26.</strong> const and static</a></li><li><a href="attributes.html"><strong aria-hidden="true">3.27.</strong> Attributes</a></li><li><a href="type-aliases.html"><strong aria-hidden="true">3.28.</strong> type aliases</a></li><li><a href="casting-between-types.html"><strong aria-hidden="true">3.29.</strong> Casting between types</a></li><li><a href="associated-types.html"><strong aria-hidden="true">3.30.</strong> Associated Types</a></li><li><a href="unsized-types.html"><strong aria-hidden="true">3.31.</strong> Unsized Types</a></li><li><a href="operators-and-overloading.html"><strong aria-hidden="true">3.32.</strong> Operators and Overloading</a></li><li><a href="deref-coercions.html"><strong aria-hidden="true">3.33.</strong> Deref coercions</a></li><li><a href="macros.html"><strong aria-hidden="true">3.34.</strong> Macros</a></li><li><a href="raw-pointers.html"><strong aria-hidden="true">3.35.</strong> Raw Pointers</a></li><li><a href="unsafe.html"><strong aria-hidden="true">3.36.</strong> unsafe</a></li></ol></li><li><a href="effective-rust.html"><strong aria-hidden="true">4.</strong> Effective Rust</a></li><li><ol class="section"><li><a href="the-stack-and-the-heap.html"><strong aria-hidden="true">4.1.</strong> The Stack and the Heap</a></li><li><a href="testing.html"><strong aria-hidden="true">4.2.</strong> Testing</a></li><li><a href="conditional-compilation.html"><strong aria-hidden="true">4.3.</strong> Conditional Compilation</a></li><li><a href="documentation.html"><strong aria-hidden="true">4.4.</strong> Documentation</a></li><li><a href="iterators.html" class="active"><strong aria-hidden="true">4.5.</strong> Iterators</a></li><li><a href="concurrency.html"><strong aria-hidden="true">4.6.</strong> Concurrency</a></li><li><a href="error-handling.html"><strong aria-hidden="true">4.7.</strong> Error Handling</a></li><li><a href="choosing-your-guarantees.html"><strong aria-hidden="true">4.8.</strong> Choosing your Guarantees</a></li><li><a href="ffi.html"><strong aria-hidden="true">4.9.</strong> FFI</a></li><li><a href="borrow-and-asref.html"><strong aria-hidden="true">4.10.</strong> Borrow and AsRef</a></li><li><a href="release-channels.html"><strong aria-hidden="true">4.11.</strong> Release Channels</a></li><li><a href="using-rust-without-the-standard-library.html"><strong aria-hidden="true">4.12.</strong> Using Rust without the standard library</a></li><li><a href="procedural-macros.html"><strong aria-hidden="true">4.13.</strong> Procedural Macros (and custom derive)</a></li></ol></li><li><a href="glossary.html"><strong aria-hidden="true">5.</strong> Glossary</a></li><li><a href="syntax-index.html"><strong aria-hidden="true">6.</strong> Syntax Index</a></li><li><a href="bibliography.html"><strong aria-hidden="true">7.</strong> Bibliography</a></li></ol>
        </nav>

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

            <div class="page">
                
                <div id="menu-bar" class="menu-bar">
                    <div id="menu-bar-sticky-container">
                        <div class="left-buttons">
                            <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                                <i class="fa fa-bars"></i>
                            </button>
                            <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                                <i class="fa fa-paint-brush"></i>
                            </button>
                            <ul id="theme-list" class="theme-popup" aria-label="submenu">
                                <li><button class="theme" id="light">Light <span class="default">(default)</span></button></li>
                                <li><button class="theme" id="rust">Rust</button></li>
                                <li><button class="theme" id="coal">Coal</button></li>
                                <li><button class="theme" id="navy">Navy</button></li>
                                <li><button class="theme" id="ayu">Ayu</button></li>
                            </ul>
                        </div>

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

                        <div class="right-buttons">
                            <a href="print.html" title="Print this book" aria-label="Print this book">
                                <i id="print-button" class="fa fa-print"></i>
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <a class="header" href="iterators.html#iterators" id="iterators"><h1>Iterators</h1></a>
<p>Let's talk about loops.</p>
<p>Remember Rust's <code>for</code> loop? Here's an example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
for x in 0..10 {
    println!(&quot;{}&quot;, x);
}
#}</code></pre></pre>
<p>Now that you know more Rust, we can talk in detail about how this works.
Ranges (the <code>0..10</code>) are 'iterators'. An iterator is something that we can
call the <code>.next()</code> method on repeatedly, and it gives us a sequence of things.</p>
<p>A range with two dots like <code>0..10</code> is inclusive on the left (so it
starts at 0) and exclusive on the right (so it ends at 9). A mathematician
would write &quot;[0, 10)&quot;.</p>
<p>Like this:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let mut range = 0..10;

loop {
    match range.next() {
        Some(x) =&gt; {
            println!(&quot;{}&quot;, x);
        },
        None =&gt; { break }
    }
}
#}</code></pre></pre>
<p>We make a mutable binding to the range, which is our iterator. We then <code>loop</code>,
with an inner <code>match</code>. This <code>match</code> is used on the result of <code>range.next()</code>,
which gives us a reference to the next value of the iterator. <code>next</code> returns an
<code>Option&lt;i32&gt;</code>, in this case, which will be <code>Some(i32)</code> when we have a value and
<code>None</code> once we run out. If we get <code>Some(i32)</code>, we print it out, and if we get
<code>None</code>, we <code>break</code> out of the loop.</p>
<p>This code sample is basically the same as our <code>for</code> loop version. The <code>for</code>
loop is a handy way to write this <code>loop</code>/<code>match</code>/<code>break</code> construct.</p>
<p><code>for</code> loops aren't the only thing that uses iterators, however. Writing your
own iterator involves implementing the <code>Iterator</code> trait. While doing that is
outside of the scope of this guide, Rust provides a number of useful iterators
to accomplish various tasks. But first, a few notes about limitations of ranges.</p>
<p>Ranges are very primitive, and we often can use better alternatives. Consider the
following Rust anti-pattern: using ranges to emulate a C-style <code>for</code> loop. Let’s
suppose you needed to iterate over the contents of a vector. You may be tempted
to write this:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let nums = vec![1, 2, 3];

for i in 0..nums.len() {
    println!(&quot;{}&quot;, nums[i]);
}
#}</code></pre></pre>
<p>This is strictly worse than using an actual iterator. You can iterate over vectors
directly, so write this:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let nums = vec![1, 2, 3];

for num in &amp;nums {
    println!(&quot;{}&quot;, num);
}
#}</code></pre></pre>
<p>There are two reasons for this. First, this more directly expresses what we
mean. We iterate through the entire vector, rather than iterating through
indexes, and then indexing the vector. Second, this version is more efficient:
the first version will have extra bounds checking because it used indexing,
<code>nums[i]</code>. But since we yield a reference to each element of the vector in turn
with the iterator, there's no bounds checking in the second example. This is
very common with iterators: we can ignore unnecessary bounds checks, but still
know that we're safe.</p>
<p>There's another detail here that's not 100% clear because of how <code>println!</code>
works. <code>num</code> is actually of type <code>&amp;i32</code>. That is, it's a reference to an <code>i32</code>,
not an <code>i32</code> itself. <code>println!</code> handles the dereferencing for us, so we don't
see it. This code works fine too:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let nums = vec![1, 2, 3];

for num in &amp;nums {
    println!(&quot;{}&quot;, *num);
}
#}</code></pre></pre>
<p>Now we're explicitly dereferencing <code>num</code>. Why does <code>&amp;nums</code> give us
references?  Firstly, because we explicitly asked it to with
<code>&amp;</code>. Secondly, if it gave us the data itself, we would have to be its
owner, which would involve making a copy of the data and giving us the
copy. With references, we're only borrowing a reference to the data,
and so it's only passing a reference, without needing to do the move.</p>
<p>So, now that we've established that ranges are often not what you want, let's
talk about what you do want instead.</p>
<p>There are three broad classes of things that are relevant here: iterators,
<em>iterator adaptors</em>, and <em>consumers</em>. Here's some definitions:</p>
<ul>
<li><em>iterators</em> give you a sequence of values.</li>
<li><em>iterator adaptors</em> operate on an iterator, producing a new iterator with a
different output sequence.</li>
<li><em>consumers</em> operate on an iterator, producing some final set of values.</li>
</ul>
<p>Let's talk about consumers first, since you've already seen an iterator, ranges.</p>
<a class="header" href="iterators.html#consumers" id="consumers"><h2>Consumers</h2></a>
<p>A <em>consumer</em> operates on an iterator, returning some kind of value or values.
The most common consumer is <code>collect()</code>. This code doesn't quite compile,
but it shows the intention:</p>
<pre><code class="language-rust ignore">let one_to_one_hundred = (1..101).collect();
</code></pre>
<p>As you can see, we call <code>collect()</code> on our iterator. <code>collect()</code> takes
as many values as the iterator will give it, and returns a collection
of the results. So why won't this compile? Rust can't determine what
type of things you want to collect, and so you need to let it know.
Here's the version that does compile:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let one_to_one_hundred = (1..101).collect::&lt;Vec&lt;i32&gt;&gt;();
#}</code></pre></pre>
<p>If you remember, the <a href="generics.html#resolving-ambiguities"><code>::&lt;&gt;</code> syntax</a>
allows us to give a type hint that tells the compiler we want a vector of
integers. You don't always need to use the whole type, though. Using a <code>_</code>
will let you provide a partial hint:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let one_to_one_hundred = (1..101).collect::&lt;Vec&lt;_&gt;&gt;();
#}</code></pre></pre>
<p>This says &quot;Collect into a <code>Vec&lt;T&gt;</code>, please, but infer what the <code>T</code> is for me.&quot;
<code>_</code> is sometimes called a &quot;type placeholder&quot; for this reason.</p>
<p><code>collect()</code> is the most common consumer, but there are others too. <code>find()</code>
is one:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let greater_than_forty_two = (0..100)
                             .find(|x| *x &gt; 42);

match greater_than_forty_two {
    Some(_) =&gt; println!(&quot;Found a match!&quot;),
    None =&gt; println!(&quot;No match found :(&quot;),
}
#}</code></pre></pre>
<p><code>find</code> takes a closure, and works on a reference to each element of an
iterator. This closure returns <code>true</code> if the element is the element we're
looking for, and <code>false</code> otherwise. <code>find</code> returns the first element satisfying
the specified predicate. Because we might not find a matching element, <code>find</code>
returns an <code>Option</code> rather than the element itself.</p>
<p>Another important consumer is <code>fold</code>. Here's what it looks like:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let sum = (1..4).fold(0, |sum, x| sum + x);
#}</code></pre></pre>
<p><code>fold()</code> is a consumer that looks like this:
<code>fold(base, |accumulator, element| ...)</code>. It takes two arguments: the first
is an element called the <em>base</em>. The second is a closure that itself takes two
arguments: the first is called the <em>accumulator</em>, and the second is an
<em>element</em>. Upon each iteration, the closure is called, and the result is the
value of the accumulator on the next iteration. On the first iteration, the
base is assigned the value of the accumulator.</p>
<p>Okay, that's a bit confusing. Let's examine the values of all of these things
in this iterator:</p>
<table><thead><tr><th> base </th><th> accumulator </th><th> element </th><th> closure result </th></tr></thead><tbody>
<tr><td> 0    </td><td> 0           </td><td> 1       </td><td> 1              </td></tr>
<tr><td> 0    </td><td> 1           </td><td> 2       </td><td> 3              </td></tr>
<tr><td> 0    </td><td> 3           </td><td> 3       </td><td> 6              </td></tr>
</tbody></table>
<p>We called <code>fold()</code> with these arguments:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# (1..4)
.fold(0, |sum, x| sum + x);
#}</code></pre></pre>
<p>So, <code>0</code> is our base, <code>sum</code> is our accumulator, and <code>x</code> is our element.  On the
first iteration, we set <code>sum</code> to <code>0</code>, and <code>x</code> is the first element of <code>nums</code>,
<code>1</code>. We then add <code>sum</code> and <code>x</code>, which gives us <code>0 + 1 = 1</code>. On the second
iteration, that value becomes our accumulator, <code>sum</code>, and the element is
the second element of the array, <code>2</code>. <code>1 + 2 = 3</code>, and so that becomes
the value of the accumulator for the last iteration. On that iteration,
<code>x</code> is the last element, <code>3</code>, and <code>3 + 3 = 6</code>, which is our final
result for our sum. <code>1 + 2 + 3 = 6</code>, and that's the result we got.</p>
<p>Whew. <code>fold</code> can be a bit strange the first few times you see it, but once it
clicks, you can use it all over the place. Any time you have a list of things,
and you want a single result, <code>fold</code> is appropriate.</p>
<p>Consumers are important due to one additional property of iterators we haven't
talked about yet: laziness. Let's talk some more about iterators, and you'll
see why consumers matter.</p>
<a class="header" href="iterators.html#iterators-1" id="iterators-1"><h2>Iterators</h2></a>
<p>As we've said before, an iterator is something that we can call the
<code>.next()</code> method on repeatedly, and it gives us a sequence of things.
Because you need to call the method, this means that iterators
can be <em>lazy</em> and not generate all of the values upfront. This code,
for example, does not actually generate the numbers <code>1-99</code>, instead
creating a value that merely represents the sequence:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let nums = 1..100;
#}</code></pre></pre>
<p>Since we didn't do anything with the range, it didn't generate the sequence.
Let's add the consumer:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let nums = (1..100).collect::&lt;Vec&lt;i32&gt;&gt;();
#}</code></pre></pre>
<p>Now, <code>collect()</code> will require that the range gives it some numbers, and so
it will do the work of generating the sequence.</p>
<p>Ranges are one of two basic iterators that you'll see. The other is <code>iter()</code>.
<code>iter()</code> can turn a vector into a simple iterator that gives you each element
in turn:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let nums = vec![1, 2, 3];

for num in nums.iter() {
   println!(&quot;{}&quot;, num);
}
#}</code></pre></pre>
<p>These two basic iterators should serve you well. There are some more
advanced iterators, including ones that are infinite.</p>
<p>That's enough about iterators. Iterator adaptors are the last concept
we need to talk about with regards to iterators. Let's get to it!</p>
<a class="header" href="iterators.html#iterator-adaptors" id="iterator-adaptors"><h2>Iterator adaptors</h2></a>
<p><em>Iterator adaptors</em> take an iterator and modify it somehow, producing
a new iterator. The simplest one is called <code>map</code>:</p>
<pre><code class="language-rust ignore">(1..100).map(|x| x + 1);
</code></pre>
<p><code>map</code> is called upon another iterator, and produces a new iterator where each
element reference has the closure it's been given as an argument called on it.
So this would give us the numbers from <code>2-100</code>. Well, almost! If you
compile the example, you'll get a warning:</p>
<pre><code class="language-text">warning: unused result which must be used: iterator adaptors are lazy and
         do nothing unless consumed, #[warn(unused_must_use)] on by default
(1..100).map(|x| x + 1);
 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<p>Laziness strikes again! That closure will never execute. This example
doesn't print any numbers:</p>
<pre><code class="language-rust ignore">(1..100).map(|x| println!(&quot;{}&quot;, x));
</code></pre>
<p>If you are trying to execute a closure on an iterator for its side effects,
use <code>for</code> instead.</p>
<p>There are tons of interesting iterator adaptors. <code>take(n)</code> will return an
iterator over the next <code>n</code> elements of the original iterator. Let's try it out
with an infinite iterator:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
for i in (1..).take(5) {
    println!(&quot;{}&quot;, i);
}
#}</code></pre></pre>
<p>This will print</p>
<pre><code class="language-text">1
2
3
4
5
</code></pre>
<p><code>filter()</code> is an adapter that takes a closure as an argument. This closure
returns <code>true</code> or <code>false</code>. The new iterator <code>filter()</code> produces
only the elements that the closure returns <code>true</code> for:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
for i in (1..100).filter(|&amp;x| x % 2 == 0) {
    println!(&quot;{}&quot;, i);
}
#}</code></pre></pre>
<p>This will print all of the even numbers between one and a hundred.
(Note that, unlike <code>map</code>, the closure passed to <code>filter</code> is passed a reference
to the element instead of the element itself. The filter predicate here uses
the <code>&amp;x</code> pattern to extract the integer. The filter closure is passed a
reference because it returns <code>true</code> or <code>false</code> instead of the element,
so the <code>filter</code> implementation must retain ownership to put the elements
into the newly constructed iterator.)</p>
<p>You can chain all three things together: start with an iterator, adapt it
a few times, and then consume the result. Check it out:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
(1..)
    .filter(|&amp;x| x % 2 == 0)
    .filter(|&amp;x| x % 3 == 0)
    .take(5)
    .collect::&lt;Vec&lt;i32&gt;&gt;();
#}</code></pre></pre>
<p>This will give you a vector containing <code>6</code>, <code>12</code>, <code>18</code>, <code>24</code>, and <code>30</code>.</p>
<p>This is just a small taste of what iterators, iterator adaptors, and consumers
can help you with. There are a number of really useful iterators, and you can
write your own as well. Iterators provide a safe, efficient way to manipulate
all kinds of lists. They're a little unusual at first, but if you play with
them, you'll get hooked. For a full list of the different iterators and
consumers, check out the <a href="../../std/iter/index.html">iterator module documentation</a>.</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        
                            <a rel="prev" href="documentation.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>
                        

                        
                            <a rel="next" href="concurrency.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>
                        

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                
                    <a href="documentation.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="concurrency.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
                
            </nav>

        </div>


        <!-- Local fallback for Font Awesome -->
        <script>
            if (getComputedStyle(document.querySelector(".fa")).fontFamily !== "FontAwesome") {
                var link = document.createElement('link');
                link.rel = 'stylesheet';
                link.type = 'text/css';
                link.href = '_FontAwesome/css/font-awesome.css';
                document.head.insertBefore(link, document.head.firstChild)
            }
        </script>

        

        

        

        

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

        <!-- Custom JS script -->
        

    </body>
</html>