|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="zh-CN" class="light" dir="ltr">
|
|
|
|
|
<head>
|
|
|
|
|
<!-- Book generated using mdBook -->
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>迭代器 - Rust语言圣经(Rust Course)</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="../../theme/style.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 affix "><a href="../../about-book.html">关于本书</a></li><li class="chapter-item affix "><a href="../../into-rust.html">进入 Rust 编程世界</a></li><li class="chapter-item affix "><a href="../../first-try/sth-you-should-not-do.html">避免从入门到放弃</a></li><li class="chapter-item affix "><a href="../../community.html">社区和锈书</a></li><li class="spacer"></li><li class="chapter-item affix "><a href="../../some-thoughts.html">Xobserve: 一切皆可观测</a></li><li class="chapter-item affix "><a href="../../beat-ai.html">BeatAI: 工程师 AI 入门圣经</a></li><li class="chapter-item affix "><li class="part-title">Rust 语言基础学习</li><li class="spacer"></li><li class="chapter-item "><a href="../../first-try/intro.html"><strong aria-hidden="true">1.</strong> 寻找牛刀,以便小试</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../first-try/installation.html"><strong aria-hidden="true">1.1.</strong> 安装 Rust 环境</a></li><li class="chapter-item "><a href="../../first-try/editor.html"><strong aria-hidden="true">1.2.</strong> 墙推 VSCode!</a></li><li class="chapter-item "><a href="../../first-try/cargo.html"><strong aria-hidden="true">1.3.</strong> 认识 Cargo</a></li><li class="chapter-item "><a href="../../first-try/hello-world.html"><strong aria-hidden="true">1.4.</strong> 不仅仅是 Hello world</a></li><li class="chapter-item "><a href="../../first-try/slowly-downloading.html"><strong aria-hidden="true">1.5.</strong> 下载依赖太慢了?</a></li></ol></li><li class="chapter-item "><a href="../../basic/intro.html"><strong aria-hidden="true">2.</strong> Rust 基础入门</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/variable.html"><strong aria-hidden="true">2.1.</strong> 变量绑定与解构</a></li><li class="chapter-item "><a href="../../basic/base-type/index.html"><strong aria-hidden="true">2.2.</strong> 基本类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/base-type/numbers.html"><strong aria-hidden="true">2.2.1.</strong> 数值类型</a></li><li class="chapter-item "><a href="../../basic/base-type/char-bool.html"><strong aria-hidden="true">2.2.2.</strong> 字符、布尔、单元类型</a></li><li class="chapter-item "><a href="../../basic/base-type/statement-expression.html"><strong aria-hidden="true">2.2.3.</strong> 语句与表达式</a></li><li class="chapter-item "><a href="../../basic/base-type/function.html"><strong aria-hidden="true">2.2.4.</strong> 函数</a></li></ol></li><li class="chapter-item "><a href="../../basic/ownership/index.html"><strong aria-hidden="true">2.3.</strong> 所有权和借用</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/ownership/ownership.html"><strong aria-hidden="true">2.3.1.</strong> 所有权</a></li><li class="chapter-item "><a href="../../basic/ownership/borrowing.html"><strong aria-hidden="true">2.3.2.</strong> 引用与借用</a></li></ol></li><li class="chapter-item "><a href="../../basic/compound-type/intro.html"><strong aria-hidden="true">2.4.</strong> 复合类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/compound-type/string-slice.html"><strong aria-hidden="true">2.4.1.</strong> 字符串与切片</a></li><li class="chapter-item "><a href="../../basic/compound-type/tuple.html"><strong aria-hidden="true">2.4.2.</strong> 元组</a></li><li class="chapter-item "><a href="../../basic/compound-type/struct.html"><strong aria-hidden="true">2.4.3.</strong> 结构体</a></li><li class="chapter-item "><a href="../../basic/compound-type/enum.html"><strong aria-hidden="true">2.4.4.</strong> 枚举</a></li><li class="chapter-item "><a href="../../basic/compound-type/array.html"><strong aria-hidden="true">2.4.5.</strong> 数组</a></l
|
|
|
|
|
</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语言圣经(Rust Course)</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-course" 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-course/edit/main/src/too-many-lists/deque/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">
|
|
|
|
|
<!-- Page table of contents -->
|
|
|
|
|
<div class="sidetoc"><nav class="pagetoc"></nav></div>
|
|
|
|
|
<main>
|
|
|
|
|
<h1 id="迭代器"><a class="header" href="#迭代器">迭代器</a></h1>
|
|
|
|
|
<p>坏男孩最令人头疼,而链表实现中,迭代器就是这样的坏男孩,所以我们放在最后来处理。</p>
|
|
|
|
|
<h2 id="intoiter"><a class="header" href="#intoiter">IntoIter</a></h2>
|
|
|
|
|
<p>由于是转移所有权,因此 <code>IntoIter</code> 一直都是最好实现的:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub struct IntoIter<T>(List<T>);
|
|
|
|
|
|
|
|
|
|
impl<T> List<T> {
|
|
|
|
|
pub fn into_iter(self) -> IntoIter<T> {
|
|
|
|
|
IntoIter(self)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T> Iterator for IntoIter<T> {
|
|
|
|
|
type Item = T;
|
|
|
|
|
fn next(&mut self) -> Option<T> {
|
|
|
|
|
self.0.pop_front()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>但是关于双向链表,有一个有趣的事实,它不仅可以从前向后迭代,还能反过来。前面实现的是传统的从前到后,那问题来了,反过来该如何实现呢?</p>
|
|
|
|
|
<p>答案是: <code>DoubleEndedIterator</code>,它继承自 <code>Iterator</code>( 通过 <a href="https://course.rs/basic/trait/advance-trait.html?highlight=supertrait#%E7%89%B9%E5%BE%81%E5%AE%9A%E4%B9%89%E4%B8%AD%E7%9A%84%E7%89%B9%E5%BE%81%E7%BA%A6%E6%9D%9F"><code>supertrait</code></a> ),因此意味着要实现该特征,首先需要实现 <code>Iterator</code>。</p>
|
|
|
|
|
<p>这样只要为 <code>DoubleEndedIterator</code> 实现 <code>next_back</code> 方法,就可以支持双向迭代了: <code>Iterator</code> 的 <code>next</code> 方法从前往后,而 <code>next_back</code> 从后向前。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>impl<T> DoubleEndedIterator for IntoIter<T> {
|
|
|
|
|
fn next_back(&mut self) -> Option<T> {
|
|
|
|
|
self.0.pop_back()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>测试下:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>#[test]
|
|
|
|
|
fn into_iter() {
|
|
|
|
|
let mut list = List::new();
|
|
|
|
|
list.push_front(1); list.push_front(2); list.push_front(3);
|
|
|
|
|
|
|
|
|
|
let mut iter = list.into_iter();
|
|
|
|
|
assert_eq!(iter.next(), Some(3));
|
|
|
|
|
assert_eq!(iter.next_back(), Some(1));
|
|
|
|
|
assert_eq!(iter.next(), Some(2));
|
|
|
|
|
assert_eq!(iter.next_back(), None);
|
|
|
|
|
assert_eq!(iter.next(), None);
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<pre><code class="language-shell">$ cargo test
|
|
|
|
|
|
|
|
|
|
Running target/debug/lists-5c71138492ad4b4a
|
|
|
|
|
|
|
|
|
|
running 11 tests
|
|
|
|
|
test fourth::test::basics ... ok
|
|
|
|
|
test fourth::test::peek ... ok
|
|
|
|
|
test fourth::test::into_iter ... ok
|
|
|
|
|
test first::test::basics ... ok
|
|
|
|
|
test second::test::basics ... ok
|
|
|
|
|
test second::test::iter ... ok
|
|
|
|
|
test second::test::iter_mut ... ok
|
|
|
|
|
test third::test::iter ... ok
|
|
|
|
|
test third::test::basics ... ok
|
|
|
|
|
test second::test::into_iter ... ok
|
|
|
|
|
test second::test::peek ... ok
|
|
|
|
|
|
|
|
|
|
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured
|
|
|
|
|
</code></pre>
|
|
|
|
|
<h2 id="iter"><a class="header" href="#iter">Iter</a></h2>
|
|
|
|
|
<p>这里又要用到糟糕的 <code>Ref</code>:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub struct Iter<'a, T>(Option<Ref<'a, Node<T>>>);
|
|
|
|
|
|
|
|
|
|
impl<T> List<T> {
|
|
|
|
|
pub fn iter(&self) -> Iter<T> {
|
|
|
|
|
Iter(self.head.as_ref().map(|head| head.borrow()))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<pre><code class="language-shell">$ cargo build
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>迄今为止一切运行正常,接下来的 <code>next</code> 实现起来会有些麻烦:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>impl<'a, T> Iterator for Iter<'a, T> {
|
|
|
|
|
type Item = Ref<'a, T>;
|
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
|
|
|
self.0.take().map(|node_ref| {
|
|
|
|
|
self.0 = node_ref.next.as_ref().map(|head| head.borrow());
|
|
|
|
|
Ref::map(node_ref, |node| &node.elem)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<pre><code class="language-shell">$ cargo build
|
|
|
|
|
|
|
|
|
|
error[E0521]: borrowed data escapes outside of closure
|
|
|
|
|
--> src/fourth.rs:155:13
|
|
|
|
|
|
|
|
|
|
|
153 | fn next(&mut self) -> Option<Self::Item> {
|
|
|
|
|
| --------- `self` is declared here, outside of the closure body
|
|
|
|
|
154 | self.0.take().map(|node_ref| {
|
|
|
|
|
155 | self.0 = node_ref.next.as_ref().map(|head| head.borrow());
|
|
|
|
|
| ^^^^^^ -------- borrow is only valid in the closure body
|
|
|
|
|
| |
|
|
|
|
|
| reference to `node_ref` escapes the closure body here
|
|
|
|
|
|
|
|
|
|
error[E0505]: cannot move out of `node_ref` because it is borrowed
|
|
|
|
|
--> src/fourth.rs:156:22
|
|
|
|
|
|
|
|
|
|
|
153 | fn next(&mut self) -> Option<Self::Item> {
|
|
|
|
|
| --------- lifetime `'1` appears in the type of `self`
|
|
|
|
|
154 | self.0.take().map(|node_ref| {
|
|
|
|
|
155 | self.0 = node_ref.next.as_ref().map(|head| head.borrow());
|
|
|
|
|
| ------ -------- borrow of `node_ref` occurs here
|
|
|
|
|
| |
|
|
|
|
|
| assignment requires that `node_ref` is borrowed for `'1`
|
|
|
|
|
156 | Ref::map(node_ref, |node| &node.elem)
|
|
|
|
|
| ^^^^^^^^ move out of `node_ref` occurs here
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>果然,膝盖又中了一箭。</p>
|
|
|
|
|
<p><code>node_ref</code> 活得不够久,跟一般的引用不同,Rust 不允许我们这样分割 <code>Ref</code>,从 <code>head.borrow()</code> 中取出的 <code>Ref</code> 只允许跟 <code>node_ref</code> 活得一样久。</p>
|
|
|
|
|
<p>而我们想要的函数是存在的:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub fn map_split<U, V, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>) where
|
|
|
|
|
F: FnOnce(&T) -> (&U, &V),
|
|
|
|
|
U: ?Sized,
|
|
|
|
|
V: ?Sized,
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>喔,这个函数定义的泛型直接晃瞎了我的眼睛。。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>fn next(&mut self) -> Option<Self::Item> {
|
|
|
|
|
self.0.take().map(|node_ref| {
|
|
|
|
|
let (next, elem) = Ref::map_split(node_ref, |node| {
|
|
|
|
|
(&node.next, &node.elem)
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
self.0 = next.as_ref().map(|head| head.borrow());
|
|
|
|
|
|
|
|
|
|
elem
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<pre><code class="language-shell">$ cargo build
|
|
|
|
|
|
|
|
|
|
Compiling lists v0.1.0 (/Users/ABeingessner/dev/temp/lists)
|
|
|
|
|
error[E0521]: borrowed data escapes outside of closure
|
|
|
|
|
--> src/fourth.rs:159:13
|
|
|
|
|
|
|
|
|
|
|
153 | fn next(&mut self) -> Option<Self::Item> {
|
|
|
|
|
| --------- `self` is declared here, outside of the closure body
|
|
|
|
|
...
|
|
|
|
|
159 | self.0 = next.as_ref().map(|head| head.borrow());
|
|
|
|
|
| ^^^^^^ ---- borrow is only valid in the closure body
|
|
|
|
|
| |
|
|
|
|
|
| reference to `next` escapes the closure body here
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>额,借用的内容只允许在闭包体中使用,看起来我们还是得用 <code>Ref::map</code> 来解决问题:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>fn next(&mut self) -> Option<Self::Item> {
|
|
|
|
|
self.0.take().map(|node_ref| {
|
|
|
|
|
let (next, elem) = Ref::map_split(node_ref, |node| {
|
|
|
|
|
(&node.next, &node.elem)
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
self.0 = if next.is_some() {
|
|
|
|
|
Some(Ref::map(next, |next| &**next.as_ref().unwrap()))
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
elem
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<pre><code class="language-shell">error[E0308]: mismatched types
|
|
|
|
|
--> src/fourth.rs:162:22
|
|
|
|
|
|
|
|
|
|
|
162 | Some(Ref::map(next, |next| &**next.as_ref().unwrap()))
|
|
|
|
|
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `fourth::Node`, found struct `std::cell::RefCell`
|
|
|
|
|
|
|
|
|
|
|
= note: expected type `std::cell::Ref<'_, fourth::Node<_>>`
|
|
|
|
|
found type `std::cell::Ref<'_, std::cell::RefCell<fourth::Node<_>>>`
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>晕, 多了一个 <code>RefCell</code> ,随着我们的对链表的逐步深入,<code>RefCell</code> 的代码嵌套变成了不可忽视的问题。</p>
|
|
|
|
|
<p>看起来我们已经无能为力了,只能试着去摆脱 <code>RefCell</code> 了。<code>Rc</code> 怎么样?我们完全可以对 <code>Rc</code> 进行完整的克隆:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub struct Iter<T>(Option<Rc<Node<T>>>);
|
|
|
|
|
|
|
|
|
|
impl<T> List<T> {
|
|
|
|
|
pub fn iter(&self) -> Iter<T> {
|
|
|
|
|
Iter(self.head.as_ref().map(|head| head.clone()))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T> Iterator for Iter<T> {
|
|
|
|
|
type Item =
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>等等,那现在返回的是什么?<code>&T</code> 还是 <code>Ref<T></code> ?</p>
|
|
|
|
|
<p>两者都不是,现在我们的 <code>Iter</code> 已经没有生命周期了:无论是 <code>&T</code> 还是 <code>Ref<T></code> 都需要我们在 <code>next</code> 之前声明好生命周期。但是我们试图从 <code>Rc</code> 中取出来的值其实是迭代器的引用。</p>
|
|
|
|
|
<p>也可以通过对 <code>Rc</code> 进行 map 获取到 <code>Rc<T></code>?但是标准库并没有给我们提供相应的功能,第三方倒是有<a href="https://crates.io/crates/owning_ref">一个</a>。</p>
|
|
|
|
|
<p>但是,即使这么做了,还有一个更大的坑在等着:一个会造成迭代器不合法的可怕幽灵。事实上,之前我们对于迭代器不合法是免疫的,但是一旦迭代器产生 <code>Rc</code>,那它们就不再会借用链表。这意味着人们可以在持有指向链表内部的指针时,还可以进行 <code>push</code> 和 <code>pop</code> 操作。</p>
|
|
|
|
|
<p>严格来说,<code>push</code> 问题不大,因为链表两端的增长不会对我们正在关注的某个子链表造成影响。</p>
|
|
|
|
|
<p>但是 <code>pop</code> 就是另一个故事了,如果在我们关注的子链表之外 <code>pop</code>, 那问题不大。但是如果是 <code>pop</code> 一个正在引用的子链表中的节点呢?那一切就完了,特别是,如果大家还试图去 unwrap <code>try_unwrap</code> 返回的 <code>Result</code> ,会直接造成整个程序的 <code>panic</code>。</p>
|
|
|
|
|
<p>仔细想一想,好像也不错,程序一切正常,除非去 <code>pop</code> 我们正在引用的节点,最美的是,就算遇到这种情况,程序也会直接崩溃,提示我们错误的发生。</p>
|
|
|
|
|
<p>其实我们大部分的努力都是为了实现隐藏的细节和优雅的 API,典型的二八原则,八成时间花在二成的细节上。但是如果不关心这些细节,可以接受自己的平凡的话,那把节点简单的到处传递就行。</p>
|
|
|
|
|
<p>总之,可以看出,内部可变性非常适合写一个安全性的应用程序,但是如果是安全性高的库,那内部可变性就有些捉襟见肘了。</p>
|
|
|
|
|
<p>最终,我选择了放弃,不再实现 <code>Iter</code> 和 <code>IterMut</code>,也许努力下,可以实现,但是。。。不愉快,算了。</p>
|
|
|
|
|
|
|
|
|
|
<div id="giscus-container"></div>
|
|
|
|
|
</main>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
|
<a rel="prev" href="../../too-many-lists/deque/symmetric.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="../../too-many-lists/deque/final-code.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="../../too-many-lists/deque/symmetric.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="../../too-many-lists/deque/final-code.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>
|
|
|
|
|
|
|
|
|
|
<script type="text/javascript" charset="utf-8">
|
|
|
|
|
var pagePath = "too-many-lists/deque/iterator.md"
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
|
|
<script src="../../assets/custom.js"></script>
|
|
|
|
|
<script src="../../assets/bigPicture.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|