You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

603 lines
79 KiB

4 months ago
<!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">Datav: 可编程的数据可视化平台和可观测性平台</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="cha
</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/basic-practice/refactoring.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>
<p>梳理我们的代码和目标后,可以整理出大致四个改进点:</p>
<ul>
<li><strong>单一且庞大的函数</strong>。对于 <code>minigrep</code> 程序而言, <code>main</code> 函数当前执行两个任务:解析命令行参数和读取文件。但随着代码的增加,<code>main</code> 函数承载的功能也将快速增加。从软件工程角度来看,一个函数具有的功能越多,越是难以阅读和维护。因此最好的办法是将大的函数拆分成更小的功能单元。</li>
<li><strong>配置变量散乱在各处</strong>。还有一点要考虑的是,当前 <code>main</code> 函数中的变量都是独立存在的,这些变量很可能被整个程序所访问,在这个背景下,独立的变量越多,越是难以维护,因此我们还可以将这些用于配置的变量整合到一个结构体中。</li>
<li><strong>细化错误提示</strong>。 目前的实现中,我们使用 <code>expect</code> 方法来输出文件读取失败时的错误信息,这个没问题,但是无论任何情况下,都只输出 <code>Should have been able to read the file</code> 这条错误提示信息,显然是有问题的,毕竟文件不存在、无权限等等都是可能的错误,一条大一统的消息无法给予用户更多的提示。</li>
<li><strong>使用错误而不是异常</strong>。 假如用户不给任何命令行参数,那我们的程序显然会无情崩溃,原因很简单:<code>index out of bounds</code>,一个数组访问越界的 <code>panic</code>,但问题来了,用户能看懂吗?甚至于未来接收的维护者能看懂吗?因此需要增加合适的错误处理代码,来给予使用者给详细友善的提示。还有就是需要在一个统一的位置来处理所有错误,利人利己!</li>
</ul>
<h2 id="分离-main-函数"><a class="header" href="#分离-main-函数">分离 main 函数</a></h2>
<p>关于如何处理庞大的 <code>main</code> 函数Rust 社区给出了统一的指导方案:</p>
<ul>
<li>将程序分割为 <code>main.rs</code><code>lib.rs</code>,并将程序的逻辑代码移动到后者内</li>
<li>命令行解析属于非常基础的功能,严格来说不算是逻辑代码的一部分,因此还可以放在 <code>main.rs</code></li>
</ul>
<p>按照这个方案,将我们的代码重新梳理后,可以得出 <code>main</code> 函数应该包含的功能:</p>
<ul>
<li>解析命令行参数</li>
<li>初始化其它配置</li>
<li>调用 <code>lib.rs</code> 中的 <code>run</code> 函数,以启动逻辑代码的运行</li>
<li>如果 <code>run</code> 返回一个错误,需要对该错误进行处理</li>
</ul>
<p>这个方案有一个很优雅的名字: 关注点分离(Separation of Concerns)。简而言之,<code>main.rs</code> 负责启动程序,<code>lib.rs</code> 负责逻辑代码的运行。从测试的角度而言,这种分离也非常合理: <code>lib.rs</code> 中的主体逻辑代码可以得到简单且充分的测试,至于 <code>main.rs</code> ?确实没办法针对其编写额外的测试代码,但是它的代码也很少啊,很容易就能保证它的正确性。</p>
<blockquote>
<p>关于如何在 Rust 中编写测试代码请参见如下章节https://course.rs/test/intro.html</p>
</blockquote>
<h3 id="分离命令行解析"><a class="header" href="#分离命令行解析">分离命令行解析</a></h3>
<p>根据之前的分析,我们需要将命令行解析的代码分离到一个单独的函数,然后将该函数放置在 <code>main.rs</code> 中:</p>
<pre><pre class="playground"><code class="language-rust edition2021">// in main.rs
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let (query, file_path) = parse_config(&amp;args);
// --省略--
}
fn parse_config(args: &amp;[String]) -&gt; (&amp;str, &amp;str) {
let query = &amp;args[1];
let file_path = &amp;args[2];
(query, file_path)
}</code></pre></pre>
<p>经过分离后,之前的设计目标完美达成,即精简了 <code>main</code> 函数,又将配置相关的代码放在了 <code>main.rs</code> 文件里。</p>
<p>看起来貌似是杀鸡用了牛刀,但是重构就是这样,一步一步,踏踏实实的前行,否则未来代码多一些后,你岂不是还要再重来一次重构?因此打好项目的基础是非常重要的!</p>
<h3 id="聚合配置变量"><a class="header" href="#聚合配置变量">聚合配置变量</a></h3>
<p>前文提到,配置变量并不适合分散的到处都是,因此使用一个结构体来统一存放是非常好的选择,这样修改后,后续的使用以及未来的代码维护都将更加简单明了。</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = parse_config(&amp;args);
println!(&quot;Searching for {}&quot;, config.query);
println!(&quot;In file {}&quot;, config.file_path);
let contents = fs::read_to_string(config.file_path)
.expect(&quot;Should have been able to read the file&quot;);
// --snip--
}
struct Config {
query: String,
file_path: String,
}
fn parse_config(args: &amp;[String]) -&gt; Config {
let query = args[1].clone();
let file_path = args[2].clone();
Config { query, file_path }
}</code></pre></pre>
<p>值得注意的是,<code>Config</code> 中存储的并不是 <code>&amp;str</code> 这样的引用类型,而是一个 <code>String</code> 字符串,也就是 <code>Config</code> 并没有去借用外部的字符串,而是拥有内部字符串的所有权。<code>clone</code> 方法的使用也可以佐证这一点。大家可以尝试不用 <code>clone</code> 方法,看看该如何解决相关的报错 :D</p>
<blockquote>
<p><code>clone</code> 的得与失</p>
<p>在上面的代码中,除了使用 <code>clone</code> ,还有其它办法来达成同样的目的,但 <code>clone</code> 无疑是最简单的方法:直接完整的复制目标数据,无需被所有权、借用等问题所困扰,但是它也有其缺点,那就是有一定的性能损耗。</p>
<p>因此是否使用 <code>clone</code> 更多是一种性能上的权衡,对于上面的使用而言,由于是配置的初始化,因此整个程序只需要执行一次,性能损耗几乎是可以忽略不计的。</p>
<p>总之,判断是否使用 <code>clone</code>:</p>
<ul>
<li>是否严肃的项目,玩具项目直接用 <code>clone</code> 就行,简单不好吗?</li>
<li>要看所在的代码路径是否是热点路径(hot path),例如执行次数较多的显然就是热点路径,热点路径就值得去使用性能更好的实现方式</li>
</ul>
</blockquote>
<p>好了,言归正传,从 <code>C</code> 语言过来的同学可能会觉得上面的代码已经很棒了,但是从 OO 语言角度来说,还差了那么一点意思。</p>
<p>下面我们试着来优化下,通过构造函数来初始化一个 <code>Config</code> 实例,而不是直接通过函数返回实例,典型的,标准库中的 <code>String::new</code> 函数就是一个范例。</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = Config::new(&amp;args);
// --snip--
}
// --snip--
impl Config {
fn new(args: &amp;[String]) -&gt; Config {
let query = args[1].clone();
let file_path = args[2].clone();
Config { query, file_path }
}
}</code></pre></pre>
<p>修改后,类似 <code>String::new</code> 的调用,我们可以通过 <code>Config::new</code> 来创建一个实例,看起来代码是不是更有那味儿了 </p>
<h2 id="错误处理"><a class="header" href="#错误处理">错误处理</a></h2>
<p>回顾一下,如果用户不输入任何命令行参数,我们的程序会怎么样?</p>
<pre><code class="language-shell">$ cargo run
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep`
thread 'main' panicked at 'index out of bounds: the len is 1 but the index is 1', src/main.rs:27:21
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code></pre>
<p>结果喜闻乐见,由于 <code>args</code> 数组没有任何元素,因此通过索引访问时,会直接报出数组访问越界的 <code>panic</code></p>
<p>报错信息对于开发者会很明确,但是对于使用者而言,就相当难理解了,下面一起来解决它。</p>
<h3 id="改进报错信息"><a class="header" href="#改进报错信息">改进报错信息</a></h3>
<p>还记得在错误处理章节,我们提到过 <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>// in main.rs
// --snip--
fn new(args: &amp;[String]) -&gt; Config {
if args.len() &lt; 3 {
panic!(&quot;not enough arguments&quot;);
}
// --snip--
<span class="boring">}</span></code></pre></pre>
<p>目的很明确,一旦传入的参数数组长度小于 3则报错并让程序崩溃推出这样后续的数组访问就不会再越界了。</p>
<pre><code class="language-shell">$ cargo run
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep`
thread 'main' panicked at 'not enough arguments', src/main.rs:26:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code></pre>
<p>不错,用户看到了更为明确的提示,但是还是有一大堆 <code>debug</code> 输出,这些我们其实是不想让用户看到的。这么看来,想要输出对用户友好的信息, <code>panic</code> 是不太适合的,它更适合告知开发者,哪里出现了问题。</p>
<h3 id="返回-result-来替代直接-panic"><a class="header" href="#返回-result-来替代直接-panic">返回 Result 来替代直接 panic</a></h3>
<p>那只能祭出之前学过的错误处理大法了,也就是返回一个 <code>Result</code>:成功时包含 <code>Config</code> 实例,失败时包含一条错误信息。</p>
<p>有一点需要额外注意下,从代码惯例的角度出发,<code>new</code> 往往不会失败,毕竟新建一个实例没道理失败,对不?因此修改为 <code>build</code> 会更加合适。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl Config {
fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
if args.len() &lt; 3 {
return Err(&quot;not enough arguments&quot;);
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
<span class="boring">}</span></code></pre></pre>
<p>这里的 <code>Result</code> 可能包含一个 <code>Config</code> 实例,也可能包含一条错误信息 <code>&amp;static str</code>,不熟悉这种字符串类型的同学可以回头看看字符串章节,代码中的字符串字面量都是该类型,且拥有 <code>'static</code> 生命周期。</p>
<h3 id="处理返回的-result"><a class="header" href="#处理返回的-result">处理返回的 Result</a></h3>
<p>接下来就是在调用 <code>build</code> 函数时,对返回的 <code>Result</code> 进行处理了,目的就是给出准确且友好的报错提示, 为了让大家更好的回顾我们修改过的内容,这里给出整体代码:</p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::env;
use std::fs;
use std::process;
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
// 对 build 返回的 `Result` 进行处理
let config = Config::build(&amp;args).unwrap_or_else(|err| {
println!(&quot;Problem parsing arguments: {err}&quot;);
process::exit(1);
});
println!(&quot;Searching for {}&quot;, config.query);
println!(&quot;In file {}&quot;, config.file_path);
let contents = fs::read_to_string(config.file_path)
.expect(&quot;Should have been able to read the file&quot;);
println!(&quot;With text:\n{contents}&quot;);
}
struct Config {
query: String,
file_path: String,
}
impl Config {
fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
if args.len() &lt; 3 {
return Err(&quot;not enough arguments&quot;);
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}</code></pre></pre>
<p>上面代码有几点值得注意:</p>
<ul>
<li><code>Result</code> 包含错误时,我们不再调用 <code>panic</code> 让程序崩溃,而是通过 <code>process::exit(1)</code> 来终结进程,其中 <code>1</code> 是一个信号值(事实上非 0 值都可以),通知调用我们程序的进程,程序是因为错误而退出的。</li>
<li><code>unwrap_or_else</code> 是定义在 <code>Result&lt;T,E&gt;</code> 上的常用方法,如果 <code>Result</code><code>Ok</code>,那该方法就类似 <code>unwrap</code>:返回 <code>Ok</code> 内部的值;如果是 <code>Err</code>,就调用<a href="https://course.rs/advance/functional-programing/closure.html">闭包</a>中的自定义代码对错误进行进一步处理</li>
</ul>
<p>综上可知,<code>config</code> 变量的值是一个 <code>Config</code> 实例,而 <code>unwrap_or_else</code> 闭包中的 <code>err</code> 参数,它的类型是 <code>'static str</code>,值是 &quot;not enough arguments&quot; 那个字符串字面量。</p>
<p>运行后,可以看到以下输出:</p>
<pre><code class="language-shell">$ cargo run
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/minigrep`
Problem parsing arguments: not enough arguments
</code></pre>
<p>终于,我们得到了自己想要的输出:既告知了用户为何报错,又消除了多余的 debug 信息,非常棒。可能有用户疑惑,<code>cargo run</code> 底下还有一大堆 <code>debug</code> 信息呢,实际上,这是 <code>cargo run</code> 自带的,大家可以试试编译成二进制可执行文件后再调用,会是什么效果。</p>
<h2 id="分离主体逻辑"><a class="header" href="#分离主体逻辑">分离主体逻辑</a></h2>
<p>接下来可以继续精简 <code>main</code> 函数,那就是将主体逻辑( 例如业务逻辑 )从 <code>main</code> 中分离出去,这样 <code>main</code> 函数就保留主流程调用,非常简洁。</p>
<pre><pre class="playground"><code class="language-rust edition2021">// in main.rs
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = Config::build(&amp;args).unwrap_or_else(|err| {
println!(&quot;Problem parsing arguments: {err}&quot;);
process::exit(1);
});
println!(&quot;Searching for {}&quot;, config.query);
println!(&quot;In file {}&quot;, config.file_path);
run(config);
}
fn run(config: Config) {
let contents = fs::read_to_string(config.file_path)
.expect(&quot;Should have been able to read the file&quot;);
println!(&quot;With text:\n{contents}&quot;);
}
// --snip--</code></pre></pre>
<p>如上所示,<code>main</code> 函数仅保留主流程各个环节的调用,一眼看过去非常简洁清晰。</p>
<p>继续之前,先请大家仔细看看 <code>run</code> 函数,你们觉得还缺少什么?提示:参考 <code>build</code> 函数的改进过程。</p>
<h3 id="使用--和特征对象来返回错误"><a class="header" href="#使用--和特征对象来返回错误">使用 ? 和特征对象来返回错误</a></h3>
<p>答案就是 <code>run</code> 函数没有错误处理,因为在文章开头我们提到过,错误处理最好统一在一个地方完成,这样极其有利于后续的代码维护。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>//in main.rs
use std::error::Error;
// --snip--
fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
let contents = fs::read_to_string(config.file_path)?;
println!(&quot;With text:\n{contents}&quot;);
Ok(())
}
<span class="boring">}</span></code></pre></pre>
<p>值得注意的是这里的 <code>Result&lt;(), Box&lt;dyn Error&gt;&gt;</code> 返回类型,首先我们的程序无需返回任何值,但是为了满足 <code>Result&lt;T,E&gt;</code> 的要求,因此使用了 <code>Ok(())</code> 返回一个单元类型 <code>()</code></p>
<p>最重要的是 <code>Box&lt;dyn Error&gt;</code> 如果按照顺序学到这里,大家应该知道这是一个<code>Error</code> 的特征对象(为了使用 <code>Error</code>,我们通过 <code>use std::error::Error;</code> 进行了引入),它表示函数返回一个类型,该类型实现了 <code>Error</code> 特征,这样我们就无需指定具体的错误类型,否则你还需要查看 <code>fs::read_to_string</code> 返回的错误类型,然后复制到我们的 <code>run</code> 函数返回中,这么做一个是麻烦,最主要的是,一旦这么做,意味着我们无法在上层调用时统一处理错误,但是 <code>Box&lt;dyn Error&gt;</code> 不同,其它函数也可以返回这个特征对象,然后调用者就可以使用统一的方式来处理不同函数返回的 <code>Box&lt;dyn Error&gt;</code></p>
<p>明白了 <code>Box&lt;dyn Error&gt;</code> 的重要战略地位,接下来大家分析下,<code>fs::read_to_string</code> 返回的具体错误类型是怎么被转化为 <code>Box&lt;dyn Error&gt;</code> 的?其实原因在之前章节都有讲过,这里就不直接给出答案了,参见 <a href="https://course.rs/basic/result-error/result.html#%E4%BC%A0%E6%92%AD%E7%95%8C%E7%9A%84%E5%A4%A7%E6%98%8E%E6%98%9F-">?-传播界的大明星</a></p>
<p>运行代码看看效果: </p>
<pre><code class="language-shell">$ cargo run the poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
warning: unused `Result` that must be used
--&gt; src/main.rs:19:5
|
19 | run(config);
| ^^^^^^^^^^^^
|
= note: `#[warn(unused_must_use)]` on by default
= note: this `Result` may be an `Err` variant, which should be handled
warning: `minigrep` (bin &quot;minigrep&quot;) generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 0.71s
Running `target/debug/minigrep the poem.txt`
Searching for the
In file poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
</code></pre>
<p>没任何问题,不过 Rust 编译器也给出了善意的提示,那就是 <code>Result</code> 并没有被使用,这可能意味着存在错误的潜在可能性。</p>
<h3 id="处理返回的错误"><a class="header" href="#处理返回的错误">处理返回的错误</a></h3>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
// --snip--
println!(&quot;Searching for {}&quot;, config.query);
println!(&quot;In file {}&quot;, config.file_path);
if let Err(e) = run(config) {
println!(&quot;Application error: {e}&quot;);
process::exit(1);
}
}</code></pre></pre>
<p>先回忆下在 <code>build</code> 函数调用时,我们怎么处理错误的?然后与这里的方式做一下对比,是不是发现了一些区别?</p>
<p>没错 <code>if let</code> 的使用让代码变得更简洁,可读性也更加好,原因是,我们并不关注 <code>run</code> 返回的 <code>Ok</code> 值,因此只需要用 <code>if let</code> 去匹配是否存在错误即可。</p>
<p>好了,截止目前,代码看起来越来越美好了,距离我们的目标也只差一个:将主体逻辑代码分离到一个独立的文件 <code>lib.rs</code> 中。</p>
<h2 id="分离逻辑代码到库包中"><a class="header" href="#分离逻辑代码到库包中">分离逻辑代码到库包中</a></h2>
<blockquote>
<p>对于 Rust 的代码组织( 包和模块 )还不熟悉的同学,强烈建议回头温习下<a href="https://course.rs/basic/crate-module/intro.html">这一章</a></p>
</blockquote>
<p>首先,创建一个 <code>src/lib.rs</code> 文件,然后将所有的非 <code>main</code> 函数都移动到其中。代码大概类似:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
// --snip--
}
}
pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
// --snip--
}
<span class="boring">}</span></code></pre></pre>
<p>为了内容的简洁性,这里忽略了具体的实现,下一步就是在 <code>main.rs</code> 中引入 <code>lib.rs</code> 中定义的 <code>Config</code> 类型。</p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::env;
use std::process;
use minigrep::Config;
fn main() {
// --snip--
let args: Vec&lt;String&gt; = env::args().collect();
let config = Config::build(&amp;args).unwrap_or_else(|err| {
println!(&quot;Problem parsing arguments: {err}&quot;);
process::exit(1);
});
println!(&quot;Searching for {}&quot;, config.query);
println!(&quot;In file {}&quot;, config.file_path);
if let Err(e) = minigrep::run(config) {
// --snip--
println!(&quot;Application error: {e}&quot;);
process::exit(1);
}
}</code></pre></pre>
<p>很明显,这里的 <code>mingrep::run</code> 的调用,以及 <code>Config</code> 的引入,跟使用其它第三方包已经没有任何区别,也意味着我们成功的将逻辑代码放置到一个独立的库包中,其它包只要引入和调用就行。</p>
<p>呼,一顿书写猛如虎,回头一看。。。这么长的篇幅就写了这么点简单的代码??只能说,我也希望像很多国内的大学教材一样,只要列出定理和解题方法,然后留下足够的习题,就万事大吉了,但是咱们不行。</p>
<p>接下来,到了最喜(令)闻(人)乐(讨)见(厌)的环节:写测试代码,一起来开心吧。</p>
<div id="giscus-container"></div>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../basic-practice/base-features.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="../basic-practice/tests.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="../basic-practice/base-features.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="../basic-practice/tests.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 = "basic-practice/refactoring.md"
</script>
<!-- Custom JS scripts -->
<script src="../assets/custom.js"></script>
<script src="../assets/bigPicture.js"></script>
</div>
</body>
</html>