Files
book/iterators.html
T

359 lines
22 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="{% block description %}{% endblock %}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="">
<link rel="stylesheet" href="book.css">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- Font Awesome -->
<link rel="stylesheet" href="http://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">
<!-- 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="http://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>
<!-- 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="introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="hello-world.html"><strong>1.2.</strong> Hello, World!</a></li><li><a href="design.html"><strong>1.3.</strong> The Design of Rust</a></li></ul></li><li><a href="tutorial.html"><strong>2.</strong> Tutorial</a></li><li><a href="basics.html"><strong>3.</strong> The Basics</a></li><li><ul class="section"><li><a href="variable-bindings.html"><strong>3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong>3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong>3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="if.html"><strong>3.5.</strong> `if`</a></li><li><a href="loops.html"><strong>3.6.</strong> Loops</a></li></ul></li><li><a href="ownership-and-borrowing.html"><strong>4.</strong> Ownership & borrowing</a></li><li><ul class="section"><li><a href="ownership.html"><strong>4.1.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>4.2.</strong> References & Borrowing</a></li><li><a href="lifetimes.html"><strong>4.3.</strong> Lifetimes</a></li></ul></li><li><a href="basic-data-types.html"><strong>5.</strong> Basic Data Types</a></li><li><ul class="section"><li><a href="structs.html"><strong>5.1.</strong> Structs</a></li><li><a href="enums.html"><strong>5.2.</strong> Enums</a></li></ul></li><li><a href="crates-and-modules.html"><strong>6.</strong> Crates & Modules</a></li><li><a href="error-handling.html"><strong>7.</strong> Error Handling</a></li><li><a href="basic-collections.html"><strong>8.</strong> Basic Collections</a></li><li><ul class="section"><li><a href="vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="hashmap.html"><strong>8.3.</strong> `HashMap<K, V>`</a></li></ul></li><li><a href="traits.html"><strong>9.</strong> Traits</a></li><li><a href="closures.html"><strong>10.</strong> Closures</a></li><li><a href="iterators.html" class="active"><strong>11.</strong> Iterators</a></li><li><a href="io.html"><strong>12.</strong> I/O</a></li><li><ul class="section"><li><a href="read-and-write.html"><strong>12.1.</strong> `Read` & `Write`</a></li><li><a href="fs.html"><strong>12.2.</strong> `std::fs`</a></li><li><a href="path.html"><strong>12.3.</strong> `std::path`</a></li><li><a href="env.html"><strong>12.4.</strong> `std::env`</a></li></ul></li><li><a href="testing.html"><strong>13.</strong> Testing</a></li><li><a href="smart-pointers.html"><strong>14.</strong> Smart Pointers</a></li><li><ul class="section"><li><a href="deref.html"><strong>14.1.</strong> `Deref`</a></li><li><a href="deref-coercions.html"><strong>14.2.</strong> `Deref` coercions</a></li><li><a href="box.html"><strong>14.3.</strong> `Box<T>`</a></li><li><a href="rc.html"><strong>14.4.</strong> `Rc<T>`</a></li></ul></li><li><a href="concurrency.html"><strong>15.</strong> Concurrency</a></li><li><ul class="section"><li><a href="threads.html"><strong>15.1.</strong> Threads</a></li><li><a href="send-and-sync.html"><strong>15.2.</strong> `Send` & `Sync`</a></li><li><a href="arc.html"><strong>15.3.</strong> `Arc<T>`</a></li><li><a href="mutex.html"><strong>15.4.</strong> `Mutex<T>`</a></li><li><a href="channels.html"><strong>15.5.</strong> `Channels`</a></li></ul></li><li><a href="unsafe-rust.html"><strong>16.</strong> Unsafe Rust</a></li><li><ul class="section"><li><a href="raw-pointers.html"><strong>16.1.</strong> Raw Pointers</a></li><li><a href="transmute.html"><strong>16.2.</strong> transmute</a></li></ul></li><li><a href="ffi.html"><strong>17.</strong> FFI</a></li><li><ul class="section"><li><a href="conditional-compilation.html"><strong>17.1.</strong> Conditional Compilation</a></li><li><a href="bindings-to-c.html"><strong>17.2.</strong> Bindings to C</a></li><li><a href="using-rust-from-other-languages.html"><strong>17.3.</strong> Using Rust from Other Languages</a></li><li><a href="static.html"><strong>17.4.</strong> `static`</a></li></ul></li><li><a href="cargo.html"><strong>18.</strong> Cargo</a></li><li><ul class="section"><li><a href="cratesio.html"><strong>18.1.</strong> Crates.io</a></li></ul></li><li><a href="advanced-type-system-features.html"><strong>19.</strong> Advanced Type System Features</a></li><li><ul class="section"><li><a href="associated-types.html"><strong>19.1.</strong> Associated Types</a></li><li><a href="trait-objects.html"><strong>19.2.</strong> Trait Objects</a></li><li><a href="ufcs.html"><strong>19.3.</strong> UFCS</a></li><li><a href="coherence.html"><strong>19.4.</strong> Coherence</a></li></ul></li><li><a href="interior-mutability.html"><strong>20.</strong> Interior mutability</a></li><li><ul class="section"><li><a href="cell.html"><strong>20.1.</strong> `Cell<T>`</a></li><li><a href="refcell.html"><strong>20.2.</strong> `RefCell<T>`</a></li></ul></li><li><a href="macros.html"><strong>21.</strong> Macros</a></li><li><a href="nightly-rust.html"><strong>22.</strong> Nightly Rust</a></li></ul>
</div>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<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"></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">
<p>% Iterators</p>
<p>Let's talk about loops.</p>
<p>Remember Rust's <code>for</code> loop? Here's an example:</p>
<pre><code class="language-rust">for x in 0..10 {
println!(&quot;{}&quot;, x);
}
</code></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>Like this:</p>
<pre><code class="language-rust">let mut range = 0..10;
loop {
match range.next() {
Some(x) =&gt; {
println!(&quot;{}&quot;, x);
},
None =&gt; { break }
}
}
</code></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 just 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><code class="language-rust">let nums = vec![1, 2, 3];
for i in 0..nums.len() {
println!(&quot;{}&quot;, nums[i]);
}
</code></pre>
<p>This is strictly worse than using an actual iterator. You can iterate over vectors
directly, so write this:</p>
<pre><code class="language-rust">let nums = vec![1, 2, 3];
for num in &amp;nums {
println!(&quot;{}&quot;, num);
}
</code></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><code class="language-rust">let nums = vec![1, 2, 3];
for num in &amp;nums {
println!(&quot;{}&quot;, *num);
}
</code></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 just borrowing a reference to the data,
and so it's just 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>
<h2>Consumers</h2>
<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><code class="language-rust">let one_to_one_hundred = (1..101).collect::&lt;Vec&lt;i32&gt;&gt;();
</code></pre>
<p>If you remember, the <code>::&lt;&gt;</code> syntax allows us to give a type hint,
and so we tell it that 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><code class="language-rust">let one_to_one_hundred = (1..101).collect::&lt;Vec&lt;_&gt;&gt;();
</code></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><code class="language-rust">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>
<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><code class="language-rust">let sum = (1..4).fold(0, |sum, x| sum + x);
</code></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 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>
<p>| base | accumulator | element | closure result |
|------|-------------|---------|----------------|
| 0 | 0 | 1 | 1 |
| 0 | 1 | 2 | 3 |
| 0 | 3 | 3 | 6 |</p>
<p>We called <code>fold()</code> with these arguments:</p>
<pre><code class="language-rust"># (1..4)
.fold(0, |sum, x| sum + x);
</code></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>
<h2>Iterators</h2>
<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><code class="language-rust">let nums = 1..100;
</code></pre>
<p>Since we didn't do anything with the range, it didn't generate the sequence.
Let's add the consumer:</p>
<pre><code class="language-rust">let nums = (1..100).collect::&lt;Vec&lt;i32&gt;&gt;();
</code></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><code class="language-rust">let nums = vec![1, 2, 3];
for num in nums.iter() {
println!(&quot;{}&quot;, num);
}
</code></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>
<h2>Iterator adaptors</h2>
<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,
just 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><code class="language-rust">for i in (1..).take(5) {
println!(&quot;{}&quot;, i);
}
</code></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><code class="language-rust">for i in (1..100).filter(|&amp;x| x % 2 == 0) {
println!(&quot;{}&quot;, i);
}
</code></pre>
<p>This will print all of the even numbers between one and a hundred.
(Note that because <code>filter</code> doesn't consume the elements that are
being iterated over, it is passed a reference to each element, and
thus the filter predicate uses the <code>&amp;x</code> pattern to extract the integer
itself.)</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><code class="language-rust">(1..)
.filter(|&amp;x| x % 2 == 0)
.filter(|&amp;x| x % 3 == 0)
.take(5)
.collect::&lt;Vec&lt;i32&gt;&gt;();
</code></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>
</div>
<!-- Mobile navigation buttons -->
<a href="closures.html" class="mobile-nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="io.html" class="mobile-nav-chapters next">
<i class="fa fa-angle-right"></i>
</a>
</div>
<a href="closures.html" class="nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="io.html" class="nav-chapters next">
<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>
<script src="highlight.js"></script>
<script src="book.js"></script>
</body>
</html>