mirror of
https://github.com/KaiserY/trpl-zh-cn
synced 2024-11-14 04:41:49 +08:00
421 lines
42 KiB
HTML
421 lines
42 KiB
HTML
|
<!DOCTYPE HTML>
|
|||
|
<html lang="en" class="light" dir="ltr">
|
|||
|
<head>
|
|||
|
<!-- Book generated using mdBook -->
|
|||
|
<meta charset="UTF-8">
|
|||
|
<title>使用迭代器处理元素序列 - Rust 程序设计语言 简体中文版</title>
|
|||
|
|
|||
|
|
|||
|
<!-- Custom HTML head -->
|
|||
|
|
|||
|
<meta name="description" content="">
|
|||
|
<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" href="highlight.css">
|
|||
|
<link rel="stylesheet" href="tomorrow-night.css">
|
|||
|
<link rel="stylesheet" href="ayu-highlight.css">
|
|||
|
|
|||
|
<!-- Custom theme stylesheets -->
|
|||
|
<link rel="stylesheet" href="ferris.css">
|
|||
|
<link rel="stylesheet" href="theme/2018-edition.css">
|
|||
|
<link rel="stylesheet" href="theme/semantic-notes.css">
|
|||
|
<link rel="stylesheet" href="theme/listing.css">
|
|||
|
|
|||
|
</head>
|
|||
|
<body class="sidebar-visible no-js">
|
|||
|
<div id="body-container">
|
|||
|
<!-- Provide site root to javascript -->
|
|||
|
<script>
|
|||
|
var path_to_root = "";
|
|||
|
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
|
|||
|
</script>
|
|||
|
|
|||
|
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
|||
|
<script>
|
|||
|
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>
|
|||
|
var theme;
|
|||
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|||
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
|||
|
var html = document.querySelector('html');
|
|||
|
html.classList.remove('light')
|
|||
|
html.classList.add(theme);
|
|||
|
var body = document.querySelector('body');
|
|||
|
body.classList.remove('no-js')
|
|||
|
body.classList.add('js');
|
|||
|
</script>
|
|||
|
|
|||
|
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
|||
|
|
|||
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|||
|
<script>
|
|||
|
var body = document.querySelector('body');
|
|||
|
var sidebar = null;
|
|||
|
var 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';
|
|||
|
body.classList.remove('sidebar-visible');
|
|||
|
body.classList.add("sidebar-" + sidebar);
|
|||
|
</script>
|
|||
|
|
|||
|
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
|||
|
<div class="sidebar-scrollbox">
|
|||
|
<ol class="chapter"><li class="chapter-item expanded affix "><a href="title-page.html">Rust 程序设计语言</a></li><li class="chapter-item expanded affix "><a href="foreword.html">前言</a></li><li class="chapter-item expanded affix "><a href="ch00-00-introduction.html">简介</a></li><li class="chapter-item expanded "><a href="ch01-00-getting-started.html"><strong aria-hidden="true">1.</strong> 入门指南</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch01-01-installation.html"><strong aria-hidden="true">1.1.</strong> 安装</a></li><li class="chapter-item expanded "><a href="ch01-02-hello-world.html"><strong aria-hidden="true">1.2.</strong> Hello, World!</a></li><li class="chapter-item expanded "><a href="ch01-03-hello-cargo.html"><strong aria-hidden="true">1.3.</strong> Hello, Cargo!</a></li></ol></li><li class="chapter-item expanded "><a href="ch02-00-guessing-game-tutorial.html"><strong aria-hidden="true">2.</strong> 写个猜数字游戏</a></li><li class="chapter-item expanded "><a href="ch03-00-common-programming-concepts.html"><strong aria-hidden="true">3.</strong> 常见编程概念</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch03-01-variables-and-mutability.html"><strong aria-hidden="true">3.1.</strong> 变量与可变性</a></li><li class="chapter-item expanded "><a href="ch03-02-data-types.html"><strong aria-hidden="true">3.2.</strong> 数据类型</a></li><li class="chapter-item expanded "><a href="ch03-03-how-functions-work.html"><strong aria-hidden="true">3.3.</strong> 函数</a></li><li class="chapter-item expanded "><a href="ch03-04-comments.html"><strong aria-hidden="true">3.4.</strong> 注释</a></li><li class="chapter-item expanded "><a href="ch03-05-control-flow.html"><strong aria-hidden="true">3.5.</strong> 控制流</a></li></ol></li><li class="chapter-item expanded "><a href="ch04-00-understanding-ownership.html"><strong aria-hidden="true">4.</strong> 认识所有权</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch04-01-what-is-ownership.html"><strong aria-hidden="true">4.1.</strong> 什么是所有权?</a></li><li class="chapter-item expanded "><a href="ch04-02-references-and-borrowing.html"><strong aria-hidden="true">4.2.</strong> 引用与借用</a></li><li class="chapter-item expanded "><a href="ch04-03-slices.html"><strong aria-hidden="true">4.3.</strong> Slice 类型</a></li></ol></li><li class="chapter-item expanded "><a href="ch05-00-structs.html"><strong aria-hidden="true">5.</strong> 使用结构体组织相关联的数据</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch05-01-defining-structs.html"><strong aria-hidden="true">5.1.</strong> 结构体的定义和实例化</a></li><li class="chapter-item expanded "><a href="ch05-02-example-structs.html"><strong aria-hidden="true">5.2.</strong> 结构体示例程序</a></li><li class="chapter-item expanded "><a href="ch05-03-method-syntax.html"><strong aria-hidden="true">5.3.</strong> 方法语法</a></li></ol></li><li class="chapter-item expanded "><a href="ch06-00-enums.html"><strong aria-hidden="true">6.</strong> 枚举和模式匹配</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch06-01-defining-an-enum.html"><strong aria-hidden="true">6.1.</strong> 枚举的定义</a></li><li class="chapter-item expanded "><a href="ch06-02-match.html"><strong aria-hidden="true">6.2.</strong> match 控制流结构</a></li><li class="chapter-item expanded "><a href="ch06-03-if-let.html"><strong aria-hidden="true">6.3.</strong> if let 简洁控制流</a></li></ol></li><li class="chapter-item expanded "><a href="ch07-00-managing-growing-projects-with-packages-crates-and-modules.html"><strong aria-hidden="true">7.</strong> 使用包、Crate 和模块管理不断增长的项目</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch07-01-packages-and-crates.html"><strong aria-hidden="true">7.1.</strong> 包和 Crate</a></li><li class="chapter-item expanded "><a h
|
|||
|
</div>
|
|||
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
|||
|
<div class="sidebar-resize-indicator"></div>
|
|||
|
</div>
|
|||
|
</nav>
|
|||
|
|
|||
|
<!-- Track and set sidebar scroll position -->
|
|||
|
<script>
|
|||
|
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
|
|||
|
sidebarScrollbox.addEventListener('click', function(e) {
|
|||
|
if (e.target.tagName === 'A') {
|
|||
|
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
|
|||
|
}
|
|||
|
}, { passive: true });
|
|||
|
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
|
|||
|
sessionStorage.removeItem('sidebar-scroll');
|
|||
|
if (sidebarScrollTop) {
|
|||
|
// preserve sidebar scroll position when navigating via links within sidebar
|
|||
|
sidebarScrollbox.scrollTop = sidebarScrollTop;
|
|||
|
} else {
|
|||
|
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
|
|||
|
var activeSection = document.querySelector('#sidebar .active');
|
|||
|
if (activeSection) {
|
|||
|
activeSection.scrollIntoView({ block: 'center' });
|
|||
|
}
|
|||
|
}
|
|||
|
</script>
|
|||
|
|
|||
|
<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="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 程序设计语言 简体中文版</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/KaiserY/trpl-zh-cn/tree/main" title="Git repository" aria-label="Git repository">
|
|||
|
<i id="git-repository-button" class="fa fa-github"></i>
|
|||
|
</a>
|
|||
|
<a href="https://github.com/KaiserY/trpl-zh-cn/edit/main/src/ch13-02-iterators.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>
|
|||
|
<h2 id="使用迭代器处理元素序列"><a class="header" href="#使用迭代器处理元素序列">使用迭代器处理元素序列</a></h2>
|
|||
|
<blockquote>
|
|||
|
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch13-02-iterators.md">ch13-02-iterators.md</a>
|
|||
|
<br>
|
|||
|
commit eabaaaa90ee6937db3690dc56f739116be55ecb2</p>
|
|||
|
</blockquote>
|
|||
|
<p>迭代器模式允许你依次对一个序列中的项执行某些操作。<strong>迭代器</strong>(<em>iterator</em>)负责遍历序列中的每一项并确定序列何时结束的逻辑。使用迭代器时,你无需自己重新实现这些逻辑。</p>
|
|||
|
<p>在 Rust 中,迭代器是 <strong>惰性的</strong>(<em>lazy</em>),这意味着在调用消费迭代器的方法之前不会执行任何操作。例如,示例 13-10 中的代码通过调用定义于 <code>Vec<T></code> 上的 <code>iter</code> 方法在一个 vector <code>v1</code> 上创建了一个迭代器。这段代码本身并没有执行任何有用的操作。</p>
|
|||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
|
|||
|
</span> let v1 = vec![1, 2, 3];
|
|||
|
|
|||
|
let v1_iter = v1.iter();
|
|||
|
<span class="boring">}</span></code></pre></pre>
|
|||
|
<p><span class="caption">示例 13-10:创建一个迭代器</span></p>
|
|||
|
<p>迭代器被储存在 <code>v1_iter</code> 变量中。一旦创建迭代器之后,可以选择用多种方式利用它。在第三章的示例 3-5 中,我们使用 <code>for</code> 循环来遍历一个数组并在每一个项上执行了一些代码。在底层它隐式地创建并接着消费了一个迭代器,不过直到现在我们都一笔带过了它具体是如何工作的。</p>
|
|||
|
<p>示例 13-11 中的例子将迭代器的创建和 <code>for</code> 循环中的使用分开。当 <code>for</code> 循环使用 <code>v1_iter</code> 中的迭代器时,迭代器中的每一个元素都会用于循环的一次迭代,并打印出每个值。</p>
|
|||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
|
|||
|
</span> let v1 = vec![1, 2, 3];
|
|||
|
|
|||
|
let v1_iter = v1.iter();
|
|||
|
|
|||
|
for val in v1_iter {
|
|||
|
println!("Got: {val}");
|
|||
|
}
|
|||
|
<span class="boring">}</span></code></pre></pre>
|
|||
|
<p><span class="caption">示例 13-11:在一个 <code>for</code> 循环中使用迭代器</span></p>
|
|||
|
<p>在标准库中没有提供迭代器的语言中,我们可能会使用一个从 0 开始的索引变量,使用这个变量索引 vector 中的值,并循环增加其值直到达到 vector 中的元素总量。</p>
|
|||
|
<p>迭代器为我们处理了所有这些逻辑,这减少了重复代码并消除了潜在的混乱。另外,迭代器的实现方式提供了对多种不同的序列使用相同逻辑的灵活性,而不仅仅是像 vector 这样可索引的数据结构。让我们看看迭代器是如何做到这些的。</p>
|
|||
|
<h3 id="iterator-trait-和-next-方法"><a class="header" href="#iterator-trait-和-next-方法"><code>Iterator</code> trait 和 <code>next</code> 方法</a></h3>
|
|||
|
<p>迭代器都实现了一个叫做 <code>Iterator</code> 的定义于标准库的 trait。这个 trait 的定义看起来像这样:</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>;
|
|||
|
|
|||
|
// 此处省略了方法的默认实现
|
|||
|
}
|
|||
|
<span class="boring">}</span></code></pre></pre>
|
|||
|
<p>注意这里有一个我们还未讲到的新语法:<code>type Item</code> 和 <code>Self::Item</code>,它们定义了 trait 的 <strong>关联类型</strong>(<em>associated type</em>)。第二十章会深入讲解关联类型,不过现在只需知道这段代码表明实现 <code>Iterator</code> trait 要求同时定义一个 <code>Item</code> 类型,这个 <code>Item</code> 类型被用作 <code>next</code> 方法的返回值类型。换句话说,<code>Item</code> 类型将是迭代器返回元素的类型。</p>
|
|||
|
<p><code>next</code> 是 <code>Iterator</code> 实现者被要求定义的唯一方法:<code>next</code> 方法,该方法每次返回迭代器中的一个项,封装在 <code>Some</code> 中,并且当迭代完成时,返回 <code>None</code>。</p>
|
|||
|
<p>可以直接调用迭代器的 <code>next</code> 方法;示例 13-12 展示了对由 vector 创建的迭代器重复调用 <code>next</code> 方法时返回的值。</p>
|
|||
|
<p><span class="filename">文件名:src/lib.rs</span></p>
|
|||
|
<pre><code class="language-rust noplayground"><span class="boring">#[cfg(test)]
|
|||
|
</span><span class="boring">mod tests {
|
|||
|
</span> #[test]
|
|||
|
fn iterator_demonstration() {
|
|||
|
let v1 = vec![1, 2, 3];
|
|||
|
|
|||
|
let mut v1_iter = v1.iter();
|
|||
|
|
|||
|
assert_eq!(v1_iter.next(), Some(&1));
|
|||
|
assert_eq!(v1_iter.next(), Some(&2));
|
|||
|
assert_eq!(v1_iter.next(), Some(&3));
|
|||
|
assert_eq!(v1_iter.next(), None);
|
|||
|
}
|
|||
|
<span class="boring">}</span></code></pre>
|
|||
|
<p><span class="caption">示例 13-12:在迭代器上(直接)调用 <code>next</code> 方法</span></p>
|
|||
|
<p>注意我们需要将 <code>v1_iter</code> 声明为可变的:在迭代器上调用 <code>next</code> 方法会改变迭代器内部的状态,该状态用于跟踪迭代器在序列中的位置。换句话说,代码 <strong>消费</strong>(consume)了,或者说用尽了迭代器。每一次 <code>next</code> 调用都会从迭代器中消费一个项。使用 <code>for</code> 循环时无需使 <code>v1_iter</code> 可变因为 <code>for</code> 循环会获取 <code>v1_iter</code> 的所有权并在后台使 <code>v1_iter</code> 可变。</p>
|
|||
|
<p>还需要注意的是,从 <code>next</code> 调用中获取的值是对 vector 中值的不可变引用。<code>iter</code> 方法生成一个不可变引用的迭代器。如果我们需要一个获取 <code>v1</code> 所有权并返回拥有所有权的迭代器,则可以调用 <code>into_iter</code> 而不是 <code>iter</code>。类似地,如果我们希望迭代可变引用,可以调用 <code>iter_mut</code> 而不是 <code>iter</code>。</p>
|
|||
|
<h3 id="消费迭代器的方法"><a class="header" href="#消费迭代器的方法">消费迭代器的方法</a></h3>
|
|||
|
<p><code>Iterator</code> trait 有一系列不同的由标准库提供默认实现的方法;你可以在 <code>Iterator</code> trait 的标准库 API 文档中找到所有这些方法。一些方法在其定义中调用了 <code>next</code> 方法,这也就是为什么在实现 <code>Iterator</code> trait 时要求实现 <code>next</code> 方法的原因。</p>
|
|||
|
<p>这些调用 <code>next</code> 方法的方法被称为 <strong>消费适配器</strong>(<em>consuming adaptors</em>),因为调用它们会消耗迭代器。一个消费适配器的例子是 <code>sum</code> 方法。这个方法获取迭代器的所有权并反复调用 <code>next</code> 来遍历迭代器,因而会消费迭代器。在遍历过程中,它将每个项累加到一个总和中,并在迭代完成时返回这个总和。示例 13-13 有一个展示 <code>sum</code> 方法使用的测试:</p>
|
|||
|
<p><span class="filename">文件名:src/lib.rs</span></p>
|
|||
|
<pre><code class="language-rust noplayground"><span class="boring">#[cfg(test)]
|
|||
|
</span><span class="boring">mod tests {
|
|||
|
</span> #[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);
|
|||
|
}
|
|||
|
<span class="boring">}</span></code></pre>
|
|||
|
<p><span class="caption">示例 13-13:调用 <code>sum</code> 方法获取迭代器所有项的总和</span></p>
|
|||
|
<p>调用 <code>sum</code> 之后不再允许使用 <code>v1_iter</code> 因为调用 <code>sum</code> 时它会获取迭代器的所有权。</p>
|
|||
|
<h3 id="产生其他迭代器的方法"><a class="header" href="#产生其他迭代器的方法">产生其他迭代器的方法</a></h3>
|
|||
|
<p><code>Iterator</code> trait 中定义了另一类方法,被称为 <strong>迭代器适配器</strong>(<em>iterator adaptors</em>),它们不会消耗当前的迭代器,而是通过改变原始迭代器的某些方面来生成不同的迭代器。</p>
|
|||
|
<p>示例 13-14 展示了一个调用迭代器适配器方法 <code>map</code> 的例子,该方法使用一个闭包对每个元素进行操作。<code>map</code> 方法返回一个新的迭代器,该迭代器生成经过修改的元素。这里的闭包创建了一个新的迭代器,其中 vector 中的每个元素都被加 1。</p>
|
|||
|
<p><span class="filename">文件名:src/main.rs</span></p>
|
|||
|
<pre><pre class="playground"><code class="language-rust not_desired_behavior edition2021"><span class="boring">fn main() {
|
|||
|
</span> let v1: Vec<i32> = vec![1, 2, 3];
|
|||
|
|
|||
|
v1.iter().map(|x| x + 1);
|
|||
|
<span class="boring">}</span></code></pre></pre>
|
|||
|
<p><span class="caption">示例 13-14:调用迭代器适配器 <code>map</code> 来创建一个新迭代器</span></p>
|
|||
|
<p>不过这些代码会产生一个警告:</p>
|
|||
|
<pre><code class="language-console">$ cargo run
|
|||
|
Compiling iterators v0.1.0 (file:///projects/iterators)
|
|||
|
warning: unused `Map` that must be used
|
|||
|
--> src/main.rs:4:5
|
|||
|
|
|
|||
|
4 | v1.iter().map(|x| x + 1);
|
|||
|
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
|||
|
|
|
|||
|
= note: iterators are lazy and do nothing unless consumed
|
|||
|
= note: `#[warn(unused_must_use)]` on by default
|
|||
|
help: use `let _ = ...` to ignore the resulting value
|
|||
|
|
|
|||
|
4 | let _ = v1.iter().map(|x| x + 1);
|
|||
|
| +++++++
|
|||
|
|
|||
|
warning: `iterators` (bin "iterators") generated 1 warning
|
|||
|
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.47s
|
|||
|
Running `target/debug/iterators`
|
|||
|
</code></pre>
|
|||
|
<p>示例 13-14 中的代码实际上并没有做任何事;所指定的闭包从未被调用过。警告提醒了我们原因所在:迭代器适配器是惰性的,因此我们需要在此处消费迭代器。</p>
|
|||
|
<p>为了修复这个警告并消费迭代器,我们将使用第十二章示例 12-1 结合 <code>env::args</code> 使用的 <code>collect</code> 方法。这个方法消费迭代器并将结果收集到一个集合数据类型中。</p>
|
|||
|
<p>在示例 13-15 中,我们将遍历由 <code>map</code> 调用生成的迭代器结果收集到一个 vector 中。这个 vector 将包含原始 vector 中每个元素加 1 的结果。</p>
|
|||
|
<p><span class="filename">文件名:src/main.rs</span></p>
|
|||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">fn main() {
|
|||
|
</span> let v1: Vec<i32> = vec![1, 2, 3];
|
|||
|
|
|||
|
let v2: Vec<_> = v1.iter().map(|x| x + 1).collect();
|
|||
|
|
|||
|
assert_eq!(v2, vec![2, 3, 4]);
|
|||
|
<span class="boring">}</span></code></pre></pre>
|
|||
|
<p><span class="caption">示例 13-15:调用 <code>map</code> 方法创建一个新迭代器,接着调用 <code>collect</code> 方法消费新迭代器并创建一个 vector</span></p>
|
|||
|
<p>由于 <code>map</code> 接受一个闭包,因此我们可以指定希望在每个元素上执行的任何操作。这是一个很好的例子,展示了如何通过闭包来自定义某些行为,同时复用 <code>Iterator</code> trait 提供的迭代行为。</p>
|
|||
|
<p>可以链式调用多个迭代器适配器来以一种可读的方式进行复杂的操作。不过因为所有的迭代器都是惰性的,你必须调用一个消费适配器方法,才能从这些迭代器适配器的调用中获取结果。</p>
|
|||
|
<h3 id="使用捕获其环境的闭包"><a class="header" href="#使用捕获其环境的闭包">使用捕获其环境的闭包</a></h3>
|
|||
|
<p>很多迭代器适配器接受闭包作为参数,而我们通常会指定捕获其环境的闭包作为迭代器适配器的参数。</p>
|
|||
|
<p>作为一个例子,我们使用 <code>filter</code> 方法来获取一个闭包。该闭包从迭代器中获取一项并返回一个 <code>bool</code>。如果闭包返回 <code>true</code>,其值将会包含在 <code>filter</code> 提供的新迭代器中。如果闭包返回 <code>false</code>,其值不会被包含。</p>
|
|||
|
<p>示例 13-16 中使用 <code>filter</code> 和一个捕获环境中变量 <code>shoe_size</code> 的闭包来遍历一个 <code>Shoe</code> 结构体集合。它只会返回指定鞋码的鞋子。</p>
|
|||
|
<p><span class="filename">文件名:src/lib.rs</span></p>
|
|||
|
<pre><code class="language-rust noplayground">#[derive(PartialEq, Debug)]
|
|||
|
struct Shoe {
|
|||
|
size: u32,
|
|||
|
style: String,
|
|||
|
}
|
|||
|
|
|||
|
fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
|
|||
|
shoes.into_iter().filter(|s| s.size == shoe_size).collect()
|
|||
|
}
|
|||
|
|
|||
|
#[cfg(test)]
|
|||
|
mod tests {
|
|||
|
use super::*;
|
|||
|
|
|||
|
#[test]
|
|||
|
fn filters_by_size() {
|
|||
|
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>
|
|||
|
<p><span class="caption">示例 13-16:使用 <code>filter</code> 方法和一个捕获 <code>shoe_size</code> 的闭包</span></p>
|
|||
|
<p><code>shoes_in_size</code> 函数获取一个鞋子 vector 的所有权和一个鞋码作为参数。它返回一个只包含指定鞋码的鞋子的 vector。</p>
|
|||
|
<p><code>shoes_in_size</code> 函数体中调用了 <code>into_iter</code> 来创建一个获取 vector 所有权的迭代器。接着调用 <code>filter</code> 将这个迭代器适配成一个只含有那些闭包返回 <code>true</code> 的元素的新迭代器。</p>
|
|||
|
<p>闭包从环境中捕获了 <code>shoe_size</code> 变量并使用其值与每一只鞋的大小作比较,只保留指定鞋码的鞋子。最终,调用 <code>collect</code> 将迭代器适配器返回的值收集进一个 vector 并返回。</p>
|
|||
|
<p>这个测试展示当调用 <code>shoes_in_size</code> 时,返回的只会是与我们指定的鞋码相同的鞋子。</p>
|
|||
|
|
|||
|
</main>
|
|||
|
|
|||
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|||
|
<!-- Mobile navigation buttons -->
|
|||
|
<a rel="prev" href="ch13-01-closures.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="ch13-03-improving-our-io-project.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="ch13-01-closures.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="ch13-03-improving-our-io-project.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="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="ferris.js"></script>
|
|||
|
|
|||
|
|
|||
|
</div>
|
|||
|
</body>
|
|||
|
</html>
|