mirror of
https://github.com/sunface/rust-by-practice.git
synced 2025-06-23 20:49:41 +00:00
521 lines
21 KiB
HTML
521 lines
21 KiB
HTML
<!DOCTYPE HTML>
|
|
<html lang="en" class="light sidebar-visible" dir="ltr">
|
|
<head>
|
|
<!-- Book generated using mdBook -->
|
|
<meta charset="UTF-8">
|
|
<title>Iterator - Rust By Practice</title>
|
|
|
|
|
|
<!-- Custom HTML head -->
|
|
|
|
<meta name="description" content="Learn Rust with Example, Exercise and real Practice, written with ❤️ by https://course.rs team">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<meta name="theme-color" content="#ffffff">
|
|
|
|
<link rel="icon" href="../favicon.svg">
|
|
<link rel="shortcut icon" href="../favicon.png">
|
|
<link rel="stylesheet" href="../css/variables.css">
|
|
<link rel="stylesheet" href="../css/general.css">
|
|
<link rel="stylesheet" href="../css/chrome.css">
|
|
<link rel="stylesheet" href="../css/print.css" media="print">
|
|
|
|
<!-- Fonts -->
|
|
<link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
|
|
<link rel="stylesheet" href="../fonts/fonts.css">
|
|
|
|
<!-- Highlight.js Stylesheets -->
|
|
<link rel="stylesheet" id="highlight-css" href="../highlight.css">
|
|
<link rel="stylesheet" id="tomorrow-night-css" href="../tomorrow-night.css">
|
|
<link rel="stylesheet" id="ayu-highlight-css" href="../ayu-highlight.css">
|
|
|
|
<!-- Custom theme stylesheets -->
|
|
<link rel="stylesheet" href="../theme/style1.css">
|
|
|
|
|
|
<!-- Provide site root and default themes to javascript -->
|
|
<script>
|
|
const path_to_root = "../";
|
|
const default_light_theme = "light";
|
|
const default_dark_theme = "navy";
|
|
</script>
|
|
<!-- Start loading toc.js asap -->
|
|
<script src="../toc.js"></script>
|
|
</head>
|
|
<body>
|
|
<div id="body-container">
|
|
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
|
<script>
|
|
try {
|
|
let theme = localStorage.getItem('mdbook-theme');
|
|
let 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>
|
|
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
|
|
let theme;
|
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
|
const html = document.documentElement;
|
|
html.classList.remove('light')
|
|
html.classList.add(theme);
|
|
html.classList.add("js");
|
|
</script>
|
|
|
|
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
<script>
|
|
let sidebar = null;
|
|
const sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
|
|
if (document.body.clientWidth >= 1080) {
|
|
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
|
sidebar = sidebar || 'visible';
|
|
} else {
|
|
sidebar = 'hidden';
|
|
}
|
|
sidebar_toggle.checked = sidebar === 'visible';
|
|
html.classList.remove('sidebar-visible');
|
|
html.classList.add("sidebar-" + sidebar);
|
|
</script>
|
|
|
|
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
|
<!-- populated by js -->
|
|
<mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
|
|
<noscript>
|
|
<iframe class="sidebar-iframe-outer" src="../toc.html"></iframe>
|
|
</noscript>
|
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
|
<div class="sidebar-resize-indicator"></div>
|
|
</div>
|
|
</nav>
|
|
|
|
<div id="page-wrapper" class="page-wrapper">
|
|
|
|
<div class="page">
|
|
<div id="menu-bar-hover-placeholder"></div>
|
|
<div id="menu-bar" class="menu-bar sticky">
|
|
<div class="left-buttons">
|
|
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
|
<i class="fa fa-bars"></i>
|
|
</label>
|
|
<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="Themes" role="menu">
|
|
<li role="none"><button role="menuitem" class="theme" id="default_theme">Auto</button></li>
|
|
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
|
|
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
|
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
|
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
|
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
|
</ul>
|
|
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
|
<i class="fa fa-search"></i>
|
|
</button>
|
|
</div>
|
|
|
|
<h1 class="menu-title">Rust By Practice</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>
|
|
<a href="https://github.com/sunface/rust-by-practice" title="Git repository" aria-label="Git repository">
|
|
<i id="git-repository-button" class="fa fa-github"></i>
|
|
</a>
|
|
<a href="https://github.com/sunface/rust-by-practice/edit/master/en/src/functional-programing/iterator.md" title="Suggest an edit" aria-label="Suggest an edit">
|
|
<i id="git-edit-button" class="fa fa-edit"></i>
|
|
</a>
|
|
|
|
</div>
|
|
</div>
|
|
|
|
<div id="search-wrapper" class="hidden">
|
|
<form id="searchbar-outer" class="searchbar-outer">
|
|
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
|
|
</form>
|
|
<div id="searchresults-outer" class="searchresults-outer hidden">
|
|
<div id="searchresults-header" class="searchresults-header"></div>
|
|
<ul id="searchresults">
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
|
<script>
|
|
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>
|
|
<h1 id="iterator"><a class="header" href="#iterator">Iterator</a></h1>
|
|
<p>The iterator pattern allows us to perform some tasks on a sequence of items in turn. An iterator is responsible for the logic of iterating over each item and determining when the sequence has finished.</p>
|
|
<h2 id="for-and-iterator"><a class="header" href="#for-and-iterator">for and iterator</a></h2>
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
let v = vec![1, 2, 3];
|
|
for x in v {
|
|
println!("{}",x)
|
|
}
|
|
}</code></pre></pre>
|
|
<p>In the code above, You may consider <code>for</code> as a simple loop, but actually it is iterating over a iterator.</p>
|
|
<p>By default <code>for</code> will apply the <code>into_iter</code> to the collection, and change it into a iterator. As a result, the following code is equivalent to previous one:</p>
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
let v = vec![1, 2, 3];
|
|
for x in v.into_iter() {
|
|
println!("{}",x)
|
|
}
|
|
}</code></pre></pre>
|
|
<ol>
|
|
<li>🌟</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">/* Refactoring the following code using iterators */
|
|
fn main() {
|
|
let arr = [0; 10];
|
|
for i in 0..arr.len() {
|
|
println!("{}",arr[i]);
|
|
}
|
|
}</code></pre></pre>
|
|
<ol start="2">
|
|
<li>🌟 One of the easiest ways to create an iterator is to use the range notion: <code>a..b</code>.</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">/* Fill in the blank */
|
|
fn main() {
|
|
let mut v = Vec::new();
|
|
for n in __ {
|
|
v.push(n);
|
|
}
|
|
|
|
assert_eq!(v.len(), 100);
|
|
}</code></pre></pre>
|
|
<h2 id="next-method"><a class="header" href="#next-method">next method</a></h2>
|
|
<p>All iterators implement a trait named <code>Iterator</code> that is defined in the standard library:</p>
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
</span><span class="boring">fn main() {
|
|
</span>pub trait Iterator {
|
|
type Item;
|
|
|
|
fn next(&mut self) -> Option<Self::Item>;
|
|
|
|
// Methods with default implementations elided
|
|
}
|
|
<span class="boring">}</span></code></pre></pre>
|
|
<p>And we can call the <code>next</code> method on iterators directly.</p>
|
|
<ol start="3">
|
|
<li>🌟🌟</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">/* Fill the blanks and fix the errors.
|
|
Using two ways if possible */
|
|
fn main() {
|
|
let v1 = vec![1, 2];
|
|
|
|
assert_eq!(v1.next(), __);
|
|
assert_eq!(v1.next(), __);
|
|
assert_eq!(v1.next(), __);
|
|
}</code></pre></pre>
|
|
<h2 id="into_iter-iter-and-iter_mut"><a class="header" href="#into_iter-iter-and-iter_mut">into_iter, iter and iter_mut</a></h2>
|
|
<p>In the previous section, we have mentioned that <code>for</code> will apply the <code>into_iter</code> to the collection, and change it into a iterator. However, this is not the only way to convert collections into iterators.</p>
|
|
<p><code>into_iter</code>, <code>iter</code>, <code>iter_mut</code>, all of them can convert a collection into iterator, but in different ways.</p>
|
|
<ul>
|
|
<li><code>into_iter</code> consumes the collection, once the collection has been consumed, it is no longer available for reuse, because its ownership has been moved within the loop.</li>
|
|
<li><code>iter</code>, this borrows each element of the collection through each iteration, thus leaving the collection untouched and available for reuse after the loop</li>
|
|
<li><code>iter_mut</code>, this mutably borrows each element of the collection, allowing for the collection to be modified in place.</li>
|
|
</ul>
|
|
<ol start="4">
|
|
<li>🌟</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">/* Make it work */
|
|
fn main() {
|
|
let arr = vec![0; 10];
|
|
for i in arr {
|
|
println!("{}", i);
|
|
}
|
|
|
|
println!("{:?}",arr);
|
|
}</code></pre></pre>
|
|
<ol start="5">
|
|
<li>🌟</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">/* Fill in the blank */
|
|
fn main() {
|
|
let mut names = vec!["Bob", "Frank", "Ferris"];
|
|
|
|
for name in names.__{
|
|
*name = match name {
|
|
&mut "Ferris" => "There is a rustacean among us!",
|
|
_ => "Hello",
|
|
}
|
|
}
|
|
|
|
println!("names: {:?}", names);
|
|
}</code></pre></pre>
|
|
<ol start="6">
|
|
<li>🌟🌟</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">/* Fill in the blank */
|
|
fn main() {
|
|
let mut values = vec![1, 2, 3];
|
|
let mut values_iter = values.__;
|
|
|
|
if let Some(v) = values_iter.__{
|
|
__
|
|
}
|
|
|
|
assert_eq!(values, vec![0, 2, 3]);
|
|
}</code></pre></pre>
|
|
<h2 id="creating-our-own-iterator"><a class="header" href="#creating-our-own-iterator">Creating our own iterator</a></h2>
|
|
<p>We can not only create iterators from collection's types, but also can create iterators by implementing the <code>Iterator</code> trait on our own types.</p>
|
|
<p><strong>Example</strong></p>
|
|
<pre><pre class="playground"><code class="language-rust edition2021">struct Counter {
|
|
count: u32,
|
|
}
|
|
|
|
impl Counter {
|
|
fn new() -> Counter {
|
|
Counter { count: 0 }
|
|
}
|
|
}
|
|
|
|
impl Iterator for Counter {
|
|
type Item = u32;
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
if self.count < 5 {
|
|
self.count += 1;
|
|
Some(self.count)
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
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>
|
|
<ol start="7">
|
|
<li>🌟🌟🌟</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">struct Fibonacci {
|
|
curr: u32,
|
|
next: u32,
|
|
}
|
|
|
|
// Implement `Iterator` for `Fibonacci`.
|
|
// The `Iterator` trait only requires a method to be defined for the `next` element.
|
|
impl Iterator for Fibonacci {
|
|
// We can refer to this type using Self::Item
|
|
type Item = u32;
|
|
|
|
/* Implement next method */
|
|
fn next(&mut self)
|
|
}
|
|
|
|
// Returns a Fibonacci sequence generator
|
|
fn fibonacci() -> Fibonacci {
|
|
Fibonacci { curr: 0, next: 1 }
|
|
}
|
|
|
|
fn main() {
|
|
let mut fib = fibonacci();
|
|
assert_eq!(fib.next(), Some(1));
|
|
assert_eq!(fib.next(), Some(1));
|
|
assert_eq!(fib.next(), Some(2));
|
|
assert_eq!(fib.next(), Some(3));
|
|
assert_eq!(fib.next(), Some(5));
|
|
}</code></pre></pre>
|
|
<h2 id="methods-that-consume-the-iterator"><a class="header" href="#methods-that-consume-the-iterator">Methods that Consume the Iterator</a></h2>
|
|
<p>The <code>Iterator</code> trait has a number of methods with default implementations provided by the standard library.</p>
|
|
<h3 id="consuming-adaptors"><a class="header" href="#consuming-adaptors">Consuming adaptors</a></h3>
|
|
<p>Some of these methods call the method <code>next</code>to use up the iterator, so they are called <em>consuming adaptors</em>.</p>
|
|
<ol start="8">
|
|
<li>🌟🌟</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">
|
|
/* Fill in the blank and fix the errors */
|
|
fn main() {
|
|
let v1 = vec![1, 2, 3];
|
|
|
|
let v1_iter = v1.iter();
|
|
|
|
// The sum method will take the ownership of the iterator and iterates through the items by repeatedly calling next method
|
|
let total = v1_iter.sum();
|
|
|
|
assert_eq!(total, __);
|
|
|
|
println!("{:?}, {:?}",v1, v1_iter);
|
|
}</code></pre></pre>
|
|
<h4 id="collect"><a class="header" href="#collect">Collect</a></h4>
|
|
<p>Other than converting a collection into an iterator, we can also <code>collect</code> the result values into a collection, <code>collect</code> will consume the iterator.</p>
|
|
<ol start="9">
|
|
<li>🌟🌟</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">/* Make it work */
|
|
use std::collections::HashMap;
|
|
fn main() {
|
|
let names = [("sunface",18), ("sunfei",18)];
|
|
let folks: HashMap<_, _> = names.into_iter().collect();
|
|
|
|
println!("{:?}",folks);
|
|
|
|
let v1: Vec<i32> = vec![1, 2, 3];
|
|
|
|
let v2 = v1.iter().collect();
|
|
|
|
assert_eq!(v2, vec![1, 2, 3]);
|
|
}</code></pre></pre>
|
|
<h3 id="iterator-adaptors"><a class="header" href="#iterator-adaptors">Iterator adaptors</a></h3>
|
|
<p>Methods allowing you to change one iterator into another iterator are known as <em>iterator adaptors</em>. You can chain multiple iterator adaptors to perform complex actions in a readable way.</p>
|
|
<p>But because <strong>all iterators are lazy</strong>, you have to call one of the consuming adapters to get results from calls to iterator adapters.</p>
|
|
<ol start="10">
|
|
<li>🌟🌟</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">/* Fill in the blanks */
|
|
fn main() {
|
|
let v1: Vec<i32> = vec![1, 2, 3];
|
|
|
|
let v2: Vec<_> = v1.iter().__.__;
|
|
|
|
assert_eq!(v2, vec![2, 3, 4]);
|
|
}</code></pre></pre>
|
|
<ol start="11">
|
|
<li>🌟🌟</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">/* Fill in the blanks */
|
|
use std::collections::HashMap;
|
|
fn main() {
|
|
let names = ["sunface", "sunfei"];
|
|
let ages = [18, 18];
|
|
let folks: HashMap<_, _> = names.into_iter().__.collect();
|
|
|
|
println!("{:?}",folks);
|
|
}</code></pre></pre>
|
|
<h4 id="using-closures-in-iterator-adaptors"><a class="header" href="#using-closures-in-iterator-adaptors">Using closures in iterator adaptors</a></h4>
|
|
<ol start="12">
|
|
<li>🌟🌟</li>
|
|
</ol>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">/* Fill in the blanks */
|
|
#[derive(PartialEq, Debug)]
|
|
struct Shoe {
|
|
size: u32,
|
|
style: String,
|
|
}
|
|
|
|
fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
|
|
shoes.into_iter().__.collect()
|
|
}
|
|
|
|
fn main() {
|
|
let shoes = vec![
|
|
Shoe {
|
|
size: 10,
|
|
style: String::from("sneaker"),
|
|
},
|
|
Shoe {
|
|
size: 13,
|
|
style: String::from("sandal"),
|
|
},
|
|
Shoe {
|
|
size: 10,
|
|
style: String::from("boot"),
|
|
},
|
|
];
|
|
|
|
let in_my_size = shoes_in_size(shoes, 10);
|
|
|
|
assert_eq!(
|
|
in_my_size,
|
|
vec![
|
|
Shoe {
|
|
size: 10,
|
|
style: String::from("sneaker")
|
|
},
|
|
Shoe {
|
|
size: 10,
|
|
style: String::from("boot")
|
|
},
|
|
]
|
|
);
|
|
}</code></pre></pre>
|
|
<blockquote>
|
|
<p>You can find the solutions <a href="https://github.com/sunface/rust-by-practice/blob/master/solutions/functional-programing/iterator.md">here</a>(under the solutions path), but only use it when you need it :)</p>
|
|
</blockquote>
|
|
|
|
</main>
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
<!-- Mobile navigation buttons -->
|
|
<a rel="prev" href="../functional-programing/closure.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 prefetch" href="../newtype-sized.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 rel="prev" href="../functional-programing/closure.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
<i class="fa fa-angle-left"></i>
|
|
</a>
|
|
|
|
<a rel="next prefetch" href="../newtype-sized.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>
|
|
|
|
|
|
|
|
|
|
<script>
|
|
window.playground_copyable = true;
|
|
</script>
|
|
|
|
<script src="../ace.js"></script>
|
|
<script src="../editor.js"></script>
|
|
<script src="../mode-rust.js"></script>
|
|
<script src="../theme-dawn.js"></script>
|
|
<script src="../theme-tomorrow_night.js"></script>
|
|
|
|
<script src="../elasticlunr.min.js"></script>
|
|
<script src="../mark.min.js"></script>
|
|
<script src="../searcher.js"></script>
|
|
|
|
<script src="../clipboard.min.js"></script>
|
|
<script src="../highlight.js"></script>
|
|
<script src="../book.js"></script>
|
|
|
|
<!-- Custom JS scripts -->
|
|
<script src="../assets/custom3.js"></script>
|
|
<script src="../assets/lang1.js"></script>
|
|
|
|
|
|
</div>
|
|
</body>
|
|
</html>
|