|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="zh-CN" class="sidebar-visible no-js light">
|
|
|
|
|
<head>
|
|
|
|
|
<!-- Book generated using mdBook -->
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>基本操作 - Rust语言圣经(Rust Course)</title>
|
|
|
|
|
<!-- Custom HTML head -->
|
|
|
|
|
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
|
|
|
|
<meta name="description" content="">
|
|
|
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
|
|
|
<meta name="theme-color" content="#ffffff" />
|
|
|
|
|
|
|
|
|
|
<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>
|
|
|
|
|
<!-- Provide site root to javascript -->
|
|
|
|
|
<script type="text/javascript">
|
|
|
|
|
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 type="text/javascript">
|
|
|
|
|
try {
|
|
|
|
|
var theme = localStorage.getItem('mdbook-theme');
|
|
|
|
|
var sidebar = localStorage.getItem('mdbook-sidebar');
|
|
|
|
|
if (theme.startsWith('"') && theme.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
|
|
|
|
}
|
|
|
|
|
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
|
|
|
|
}
|
|
|
|
|
} catch (e) { }
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Set the theme before any content is loaded, prevents flash -->
|
|
|
|
|
<script type="text/javascript">
|
|
|
|
|
var theme;
|
|
|
|
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|
|
|
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
|
|
|
|
var html = document.querySelector('html');
|
|
|
|
|
html.classList.remove('no-js')
|
|
|
|
|
html.classList.remove('light')
|
|
|
|
|
html.classList.add(theme);
|
|
|
|
|
html.classList.add('js');
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
|
|
|
<script type="text/javascript">
|
|
|
|
|
var html = document.querySelector('html');
|
|
|
|
|
var sidebar = 'hidden';
|
|
|
|
|
if (document.body.clientWidth >= 1080) {
|
|
|
|
|
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
|
|
|
|
sidebar = sidebar || 'visible';
|
|
|
|
|
}
|
|
|
|
|
html.classList.remove('sidebar-visible');
|
|
|
|
|
html.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="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></li></ol></li><li class="chapter-item "><a href="../../basic/flow-control.html"><strong aria-hidden="true">2.5.</strong> 流程控制</a></li><li class="chapter-item "><a href="../../basic/match-pattern/intro.html"><strong aria-hidde
|
|
|
|
|
</div>
|
|
|
|
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></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 bordered">
|
|
|
|
|
<div class="left-buttons">
|
|
|
|
|
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
|
|
|
|
<i class="fa fa-bars"></i>
|
|
|
|
|
</button>
|
|
|
|
|
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
|
|
|
|
<i class="fa fa-paint-brush"></i>
|
|
|
|
|
</button>
|
|
|
|
|
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="light">Light (default)</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/bad-stack/basic-operations.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 type="text/javascript">
|
|
|
|
|
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
|
|
|
|
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
|
|
|
|
|
|
|
|
|
// Get viewed page store
|
|
|
|
|
var viewed_key = 'mdbook-viewed';
|
|
|
|
|
var viewed_map = {};
|
|
|
|
|
try {
|
|
|
|
|
var viewed_storage = localStorage.getItem(viewed_key);
|
|
|
|
|
if (viewed_storage) {
|
|
|
|
|
viewed_map = JSON.parse(viewed_storage)
|
|
|
|
|
}
|
|
|
|
|
} catch (e) { }
|
|
|
|
|
|
|
|
|
|
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
|
|
|
|
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
|
|
|
|
|
|
|
|
|
// Apply viewed style
|
|
|
|
|
if (viewed_map[link.pathname]) {
|
|
|
|
|
link.classList.add('md-viewed')
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Mark viewed after 30s
|
|
|
|
|
setTimeout(function() {
|
|
|
|
|
viewed_map[location.pathname] = 1;
|
|
|
|
|
localStorage.setItem(viewed_key, JSON.stringify(viewed_map));
|
|
|
|
|
}, 30000)
|
|
|
|
|
</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>这个章节我们一起来为新创建的 <code>List</code> 定义一些基本操作,首先从创建链表开始。</p>
|
|
|
|
|
<h2 id="new"><a class="header" href="#new">New</a></h2>
|
|
|
|
|
<p>为了将实际的代码跟类型关联在一起,我们需要使用 <code>impl</code> 语句块:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>impl List {
|
|
|
|
|
// TODO
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p>下一步就是创建一个关联函数,用于构建 <code>List</code> 的新实例,该函数的作用类似于其他语言的构造函数。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>impl List {
|
|
|
|
|
pub fn new() -> Self {
|
|
|
|
|
List { head: Link::Empty }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p>学习链接: <a href="https://course.rs/basic/method.html#%E5%85%B3%E8%81%94%E5%87%BD%E6%95%B0">impl、关联函数</a>、<a href="https://course.rs/basic/trait/trait-object.html?highlight=Self#self-%E4%B8%8E-self">Self</a> </p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<h2 id="push"><a class="header" href="#push">Push</a></h2>
|
|
|
|
|
<p>在开始实现之前,你需要先了解 <a href="https://course.rs/basic/method.html#selfself-%E5%92%8C-mut-self">self、&self、&mut sef</a> 这几个概念。</p>
|
|
|
|
|
<p>在创建链表后,下一步就是往链表中插入新的元素,由于 <code>push</code> 会改变链表,因此我们使用 <code>&mut self</code> 的方法签名:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>impl List {
|
|
|
|
|
pub fn push(&mut self, elem: i32) {
|
|
|
|
|
// TODO
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p>根据之前的数据定义,首先需要创建一个 <code>Node</code> 来存放该元素:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub fn push(&mut self, elem: i32) {
|
|
|
|
|
let new_node = Node {
|
|
|
|
|
elem: elem,
|
|
|
|
|
next: ?????
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p>下一步需要让该节点指向之前的旧 <code>List</code>:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub fn push(&mut self, elem: i32) {
|
|
|
|
|
let new_node = Node {
|
|
|
|
|
elem: elem,
|
|
|
|
|
next: self.head,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<pre><code class="language-shell">error[E0507]: cannot move out of `self.head` which is behind a mutable reference
|
|
|
|
|
--> src/first.rs:23:19
|
|
|
|
|
|
|
|
|
|
|
23 | next: self.head,
|
|
|
|
|
| ^^^^^^^^^ move occurs because `self.head` has type `Link`, which does not implement the `Copy` trait
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>但是,如上所示,这段代码会报错,因为试图将借用的值 <code>self</code> 中的 <code>head</code> 字段的所有权转移给 <code>next</code> ,在 Rust 中这是不被允许的。那如果我们试图将值再放回去呢?</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub fn push(&mut self, elem: i32) {
|
|
|
|
|
let new_node = Box::new(Node {
|
|
|
|
|
elem: elem,
|
|
|
|
|
next: self.head,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
self.head = Link::More(new_node);
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p>其实在写之前,应该就预料到结果了,显然这也是不行的,虽然从我们的角度来看还挺正常的,但是 Rust 并不会接受(有多种原因,其中主要的是<a href="https://doc.rust-lang.org/nightly/nomicon/exception-safety.html">Exception safety</a>)。</p>
|
|
|
|
|
<p>我们需要一个办法,让 Rust 不再阻挠我们,其中一个可行的办法是使用 <code>clone</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 List {
|
|
|
|
|
head: Link,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
|
enum Link {
|
|
|
|
|
Empty,
|
|
|
|
|
More(Box<Node>),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
|
struct Node {
|
|
|
|
|
elem: i32,
|
|
|
|
|
next: Link,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl List {
|
|
|
|
|
pub fn new() -> Self {
|
|
|
|
|
List { head: Link::Empty }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn push(&mut self, elem: i32) {
|
|
|
|
|
let new_node = Node {
|
|
|
|
|
elem: elem,
|
|
|
|
|
next: self.head.clone(),
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p><code>clone</code> 用起来简单,且可解万愁,但是。。。既然是链表,性能那自然是很重要的,特别是要封装成库给其他代码使用时,那性能更是重中之重。</p>
|
|
|
|
|
<p>没办法了,我们只能向大名鼎鼎的 Rust 黑客 Indiana Jones求助了:
|
|
|
|
|
<img src="https://rust-unofficial.github.io/too-many-lists/img/indy.gif" /></p>
|
|
|
|
|
<p>经过一番诚心祈愿,Indy 建议我们使用 <code>mem::replace</code> 秘技。这个非常有用的函数允许我们从一个借用中偷出一个值的同时再放入一个新值。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub fn push(&mut self, elem: i32) {
|
|
|
|
|
let new_node = Box::new(Node {
|
|
|
|
|
elem: elem,
|
|
|
|
|
next: std::mem::replace(&mut self.head, Link::Empty),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
self.head = Link::More(new_node);
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p>这里,我们从借用 <code>self</code> 中偷出了它的值 <code>head</code> 并赋予给 <code>next</code> 字段,同时将一个新值 <code>Link::Empty</code> 放入到 <code>head</code> 中,成功完成偷梁换柱。不得不说,这个做法非常刺激,但是很不幸的是,目前为止,最好的办法可能也只能是它了。</p>
|
|
|
|
|
<p>但是不管怎样,我们成功的完成了 <code>push</code> 方法,下面再来看看 <code>pop</code>。</p>
|
|
|
|
|
<h2 id="pop"><a class="header" href="#pop">Pop</a></h2>
|
|
|
|
|
<p><code>push</code> 是插入元素,那 <code>pop</code> 自然就是推出一个元素,因此也需要使用 <code>&mut self</code>,除此之外,推出的元素需要被返回,这样调用者就可以获取该元素:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub fn pop(&mut self) -> Option<i32> {
|
|
|
|
|
// TODO
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p>我们还需要一个办法来根据 <code>Link</code> 是否有值进行不同的处理,这个可以使用 <code>match</code> 来进行模式匹配:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub fn pop(&mut self) -> Option<i32> {
|
|
|
|
|
match self.head {
|
|
|
|
|
Link::Empty => {
|
|
|
|
|
// TODO
|
|
|
|
|
}
|
|
|
|
|
Link::More(node) => {
|
|
|
|
|
// TODO
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p>目前的代码显然会报错,因为函数的返回值是 <code>Option<T></code> 枚举,而目前的返回值是 <a href="https://course.rs/basic/base-type/function.html#%E6%97%A0%E8%BF%94%E5%9B%9E%E5%80%BC"><code>()</code></a>。当然,我们可以返回一个<code>Option<T></code> 的枚举成员 <code>None</code>,但是一个更好的做法是使用 <code>unimplemented!()</code>,该宏可以明确地说明目前的代码还没有实现,一旦代码执行到 <code>unimplemented!()</code> 的位置,就会发生一个 <code>panic</code>。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub fn pop(&mut self) -> Option<i32> {
|
|
|
|
|
match self.head {
|
|
|
|
|
Link::Empty => {
|
|
|
|
|
// TODO
|
|
|
|
|
}
|
|
|
|
|
Link::More(node) => {
|
|
|
|
|
// TODO
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
unimplemented!()
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p><code>panics</code> 是一种<a href="https://course.rs/basic/base-type/function.html?search=#%E6%B0%B8%E4%B8%8D%E8%BF%94%E5%9B%9E%E7%9A%84%E5%87%BD%E6%95%B0">发散函数</a>,该函数永不返回任何值,因此可以用于需要返回任何类型的地方。这句话很不好理解,但是从上面的代码中可以看出 <code>unimplemented!()</code> 是永不返回的函数,但是它却可以用于一个返回 <code>Option<i32></code> 的函数中来替代返回值。</p>
|
|
|
|
|
<p>以上代码果不其然又报错了:</p>
|
|
|
|
|
<pre><code class="language-shell">$ cargo build
|
|
|
|
|
|
|
|
|
|
error[E0507]: cannot move out of borrowed content
|
|
|
|
|
--> src/first.rs:28:15
|
|
|
|
|
|
|
|
|
|
|
28 | match self.head {
|
|
|
|
|
| ^^^^^^^^^
|
|
|
|
|
| |
|
|
|
|
|
| cannot move out of borrowed content
|
|
|
|
|
| help: consider borrowing here: `&self.head`
|
|
|
|
|
...
|
|
|
|
|
32 | Link::More(node) => {
|
|
|
|
|
| ---- data moved here
|
|
|
|
|
|
|
|
|
|
|
note: move occurs because `node` has type `std::boxed::Box<first::Node>`, which does not implement the `Copy` trait
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>好在编译器偷偷提示了我们使用借用来替代所有权转移: <code>&self.head</code>。修改后,如下:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub fn pop(&mut self) -> Option<i32> {
|
|
|
|
|
match &self.head {
|
|
|
|
|
Link::Empty => {
|
|
|
|
|
// TODO
|
|
|
|
|
}
|
|
|
|
|
Link::More(node) => {
|
|
|
|
|
// TODO
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
unimplemented!()
|
|
|
|
|
}
|
|
|
|
|
<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>pub fn pop(&mut self) -> Option<i32> {
|
|
|
|
|
let result;
|
|
|
|
|
match &self.head {
|
|
|
|
|
Link::Empty => {
|
|
|
|
|
result = None;
|
|
|
|
|
}
|
|
|
|
|
Link::More(node) => {
|
|
|
|
|
result = Some(node.elem);
|
|
|
|
|
self.head = node.next;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
result
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p>当链表为 <code>Empty</code> 时,返回一个 <code>None</code>,表示我们没有 <code>pop</code> 到任何元素;若不为空,则返回第一个元素,并将 <code>head</code> 指向下一个节点 <code>node.next</code>。但是这段代码又报错了:</p>
|
|
|
|
|
<pre><code class="language-shell">error[E0507]: cannot move out of `node.next` which is behind a shared reference
|
|
|
|
|
--> src/first.rs:37:29
|
|
|
|
|
|
|
|
|
|
|
37 | self.head = node.next;
|
|
|
|
|
| ^^^^^^^^^ move occurs because `node.next` has type `Link`, which does not implement the `Copy` trait
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>原因是试图转移 <code>node</code> 的所有权,但只有它的引用。回头仔细看看代码,会发现这里的关键是我们希望移除一些东西,这意味着需要通过值的方式获取链表的 head。看来只能故技重施了:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub fn pop(&mut self) -> Option<i32> {
|
|
|
|
|
let result;
|
|
|
|
|
match std::mem::replace(&mut self.head, Link::Empty) {
|
|
|
|
|
Link::Empty => {
|
|
|
|
|
result = None;
|
|
|
|
|
}
|
|
|
|
|
Link::More(node) => {
|
|
|
|
|
result = Some(node.elem);
|
|
|
|
|
self.head = node.next;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
result
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p>我们将 <code>self.head</code> 的值偷出来,然后再将 <code>Link::Empty</code> 填回到 <code>self.head</code> 中。此时用于 <code>match</code> 匹配的就是一个拥有所有权的值类型,而不是之前的引用类型。</p>
|
|
|
|
|
<p>事实上,上面的代码有些啰嗦,我们可以直接在 <code>match</code> 的两个分支中通过表达式进行返回:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">
|
|
|
|
|
<span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub fn pop(&mut self) -> Option<i32> {
|
|
|
|
|
match std::mem::replace(&mut self.head, Link::Empty) {
|
|
|
|
|
Link::Empty => None,
|
|
|
|
|
Link::More(node) => {
|
|
|
|
|
self.head = node.next;
|
|
|
|
|
Some(node.elem)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}
|
|
|
|
|
</span></code></pre></pre>
|
|
|
|
|
<p>这样修改后,代码就更加简洁,可读性也更好了,至此链表的基本操作已经完成,下面让我们写一个测试代码来测试下它的功能和正确性。</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/bad-stack/layout.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
|
|
|
<i class="fa fa-angle-left"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a rel="next" href="../../too-many-lists/bad-stack/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/bad-stack/layout.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" href="../../too-many-lists/bad-stack/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 type="text/javascript">
|
|
|
|
|
window.playground_copyable = true;
|
|
|
|
|
</script>
|
|
|
|
|
<script src="../../ace.js" type="text/javascript" charset="utf-8"></script>
|
|
|
|
|
<script src="../../editor.js" type="text/javascript" charset="utf-8"></script>
|
|
|
|
|
<script src="../../mode-rust.js" type="text/javascript" charset="utf-8"></script>
|
|
|
|
|
<script src="../../theme-dawn.js" type="text/javascript" charset="utf-8"></script>
|
|
|
|
|
<script src="../../theme-tomorrow_night.js" type="text/javascript" charset="utf-8"></script>
|
|
|
|
|
<script src="../../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
|
|
|
|
|
<script src="../../mark.min.js" type="text/javascript" charset="utf-8"></script>
|
|
|
|
|
<script src="../../searcher.js" type="text/javascript" charset="utf-8"></script>
|
|
|
|
|
<script src="../../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
|
|
|
|
|
<script src="../../highlight.js" type="text/javascript" charset="utf-8"></script>
|
|
|
|
|
<script src="../../book.js" type="text/javascript" charset="utf-8"></script>
|
|
|
|
|
<script type="text/javascript" charset="utf-8">
|
|
|
|
|
var pagePath = "too-many-lists/bad-stack/basic-operations.md"
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
|
|
<script type="text/javascript" src="../../assets/custom.js"></script>
|
|
|
|
|
<script type="text/javascript" src="../../assets/bigPicture.js"></script>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|