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.
568tools/tools/rust-course/basic/lifetime.html

805 lines
97 KiB

<!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 expanded "><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-hidden="true">2.6.</strong> 模式匹配</a><a class="toggle"><div></div></a>
</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/basic/lifetime.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>各位读者,之前的集合章节挺简单吧?是不是安逸了挺久了?要不咱们加点料?来试试 Rust 中令人闻风丧胆的生命周期?</p>
<p>生命周期,简而言之就是引用的有效作用域。在大多数时候,我们无需手动的声明生命周期,因为编译器可以自动进行推导,用类型来类比下:</p>
<ul>
<li>就像编译器大部分时候可以自动推导类型 &lt;-&gt; 一样,编译器大多数时候也可以自动推导生命周期</li>
<li>在多种类型存在时,编译器往往要求我们手动标明类型 &lt;-&gt; 当多个生命周期存在,且编译器无法推导出某个引用的生命周期时,就需要我们手动标明生命周期</li>
</ul>
<p>Rust 生命周期之所以难,是因为这个概念对于我们来说是全新的,没有其它编程语言的经验可以借鉴。当你觉得难的时候,不用过于担心,这个难对于所有人都是平等的,多点付出就能早点解决此拦路虎,同时本书也会尽力帮助大家减少学习难度(生命周期很可能是 Rust 中最难的部分)。</p>
<h2 id="悬垂指针和生命周期"><a class="header" href="#悬垂指针和生命周期">悬垂指针和生命周期</a></h2>
<p>生命周期的主要作用是避免悬垂引用,它会导致程序引用了本不该引用的数据:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>{
let r;
{
let x = 5;
r = &amp;x;
}
println!(&quot;r: {}&quot;, r);
}
<span class="boring">}
</span></code></pre></pre>
<p>这段代码有几点值得注意:</p>
<ul>
<li><code>let r;</code> 的声明方式貌似存在使用 <code>null</code> 的风险,实际上,当我们不初始化它就使用时,编译器会给予报错</li>
<li><code>r</code> 引用了内部花括号中的 <code>x</code> 变量,但是 <code>x</code> 会在内部花括号 <code>}</code> 处被释放,因此回到外部花括号后,<code>r</code> 会引用一个无效的 <code>x</code></li>
</ul>
<p>此处 <code>r</code> 就是一个悬垂指针,它引用了提前被释放的变量 <code>x</code>,可以预料到,这段代码会报错:</p>
<pre><code class="language-console">error[E0597]: `x` does not live long enough // `x` 活得不够久
--&gt; src/main.rs:7:17
|
7 | r = &amp;x;
| ^^ borrowed value does not live long enough // 被借用的 `x` 活得不够久
8 | }
| - `x` dropped here while still borrowed // `x` 在这里被丢弃,但是它依然还在被借用
9 |
10 | println!(&quot;r: {}&quot;, r);
| - borrow later used here // 对 `x` 的借用在此处被使用
</code></pre>
<p>在这里 <code>r</code> 拥有更大的作用域,或者说<strong>活得更久</strong>。如果 Rust 不阻止该悬垂引用的发生,那么当 <code>x</code> 被释放后,<code>r</code> 所引用的值就不再是合法的,会导致我们程序发生异常行为,且该异常行为有时候会很难被发现。</p>
<h2 id="借用检查"><a class="header" href="#借用检查">借用检查</a></h2>
<p>为了保证 Rust 的所有权和借用的正确性Rust 使用了一个借用检查器(Borrow checker),来检查我们程序的借用正确性:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>{
let r; // ---------+-- 'a
// |
{ // |
let x = 5; // -+-- 'b |
r = &amp;x; // | |
} // -+ |
// |
println!(&quot;r: {}&quot;, r); // |
} // ---------+
<span class="boring">}
</span></code></pre></pre>
<p>这段代码和之前的一模一样,唯一的区别在于增加了对变量生命周期的注释。这里,<code>r</code> 变量被赋予了生命周期 <code>'a</code><code>x</code> 被赋予了生命周期 <code>'b</code>,从图示上可以明显看出生命周期 <code>'b</code><code>'a</code> 小很多。</p>
<p>在编译期Rust 会比较两个变量的生命周期,结果发现 <code>r</code> 明明拥有生命周期 <code>'a</code>,但是却引用了一个小得多的生命周期 <code>'b</code>,在这种情况下,编译器会认为我们的程序存在风险,因此拒绝运行。</p>
<p>如果想要编译通过,也很简单,只要 <code>'b</code><code>'a</code> 大就好。总之,<code>x</code> 变量只要比 <code>r</code> 活得久,那么 <code>r</code> 就能随意引用 <code>x</code> 且不会存在危险:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>{
let x = 5; // ----------+-- 'b
// |
let r = &amp;x; // --+-- 'a |
// | |
println!(&quot;r: {}&quot;, r); // | |
// --+ |
} // ----------+
<span class="boring">}
</span></code></pre></pre>
<p>根据之前的结论,我们重新实现了代码,现在 <code>x</code> 的生命周期 <code>'b</code> 大于 <code>r</code> 的生命周期 <code>'a</code>,因此 <code>r</code><code>x</code> 的引用是安全的。</p>
<p>通过之前的内容,我们了解了何为生命周期,也了解了 Rust 如何利用生命周期来确保引用是合法的,下面来看看函数中的生命周期。</p>
<h2 id="函数中的生命周期"><a class="header" href="#函数中的生命周期">函数中的生命周期</a></h2>
<p>先来考虑一个例子 - 返回两个字符串切片中较长的那个,该函数的参数是两个字符串切片,返回值也是字符串切片:</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let string1 = String::from(&quot;abcd&quot;);
let string2 = &quot;xyz&quot;;
let result = longest(string1.as_str(), string2);
println!(&quot;The longest string is {}&quot;, result);
}
</code></pre></pre>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
if x.len() &gt; y.len() {
x
} else {
y
}
}
<span class="boring">}
</span></code></pre></pre>
<p>这段 <code>longest</code> 实现,非常标准优美,就连多余的 <code>return</code> 和分号都没有,可是现实总是给我们重重一击:</p>
<pre><code class="language-console">error[E0106]: missing lifetime specifier
--&gt; src/main.rs:9:33
|
9 | fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
| ---- ---- ^ expected named lifetime parameter // 参数需要一个生命周期
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is
borrowed from `x` or `y`
= 帮助: 该函数的返回值是一个引用类型,但是函数签名无法说明,该引用是借用自 `x` 还是 `y`
help: consider introducing a named lifetime parameter // 考虑引入一个生命周期
|
9 | fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
| ^^^^ ^^^^^^^ ^^^^^^^ ^^^
</code></pre>
<p>喔,这真是一个复杂的提示,那感觉就好像是生命周期去非诚勿扰相亲,结果在初印象环节就 23 盏灯全灭。等等,先别急,如果你仔细阅读,就会发现,其实主要是编译器无法知道该函数的返回值到底引用 <code>x</code> 还是 <code>y</code> <strong>因为编译器需要知道这些,来确保函数调用后的引用生命周期分析</strong></p>
<p>不过说来尴尬,就这个函数而言,我们也不知道返回值到底引用哪个,因为一个分支返回 <code>x</code>,另一个分支返回 <code>y</code>...这可咋办?先来分析下。</p>
<p>我们在定义该函数时,首先无法知道传递给函数的具体值,因此到底是 <code>if</code> 还是 <code>else</code> 被执行,无从得知。其次,传入引用的具体生命周期也无法知道,因此也不能像之前的例子那样通过分析生命周期来确定引用是否有效。同时,编译器的借用检查也无法推导出返回值的生命周期,因为它不知道 <code>x</code><code>y</code> 的生命周期跟返回值的生命周期之间的关系是怎样的(说实话,人都搞不清,何况编译器这个大聪明)。</p>
<p>因此,这时就回到了文章开头说的内容:在存在多个引用时,编译器有时会无法自动推导生命周期,此时就需要我们手动去标注,通过为参数标注合适的生命周期来帮助编译器进行借用检查的分析。</p>
<h2 id="生命周期标注语法"><a class="header" href="#生命周期标注语法">生命周期标注语法</a></h2>
<blockquote>
<p>生命周期标注并不会改变任何引用的实际作用域 -- 鲁迅</p>
</blockquote>
<p>鲁迅说过的话,总是值得重点标注,当你未来更加理解生命周期时,你才会发现这句话的精髓和重要!现在先简单记住,<strong>标记的生命周期只是为了取悦编译器,让编译器不要难为我们</strong>,记住了吗?没记住,再回头看一遍,这对未来你遇到生命周期问题时会有很大的帮助!</p>
<p>在很多时候编译器是很聪明的,但是总有些时候,它会化身大聪明,自以为什么都很懂,然后去拒绝我们代码的执行,此时,就需要我们通过生命周期标注来告诉这个大聪明:别自作聪明了,听我的就好。</p>
<p>例如一个变量,只能活一个花括号,那么就算你给它标注一个活全局的生命周期,它还是会在前面的花括号结束处被释放掉,并不会真的全局存活。</p>
<p>生命周期的语法也颇为与众不同,以 <code>'</code> 开头,名称往往是一个单独的小写字母,大多数人都用 <code>'a</code> 来作为生命周期的名称。 如果是引用类型的参数,那么生命周期会位于引用符号 <code>&amp;</code> 之后,并用一个空格来将生命周期和引用参数分隔开:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>&amp;i32 // 一个引用
&amp;'a i32 // 具有显式生命周期的引用
&amp;'a mut i32 // 具有显式生命周期的可变引用
<span class="boring">}
</span></code></pre></pre>
<p>一个生命周期标注,它自身并不具有什么意义,因为生命周期的作用就是告诉编译器多个引用之间的关系。例如,有一个函数,它的第一个参数 <code>first</code> 是一个指向 <code>i32</code> 类型的引用,具有生命周期 <code>'a</code>,该函数还有另一个参数 <code>second</code>,它也是指向 <code>i32</code> 类型的引用,并且同样具有生命周期 <code>'a</code>。此处生命周期标注仅仅说明,<strong>这两个参数 <code>first</code><code>second</code> 至少活得和'a 一样久,至于到底活多久或者哪个活得更久,抱歉我们都无法得知</strong></p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn useless&lt;'a&gt;(first: &amp;'a i32, second: &amp;'a i32) {}
<span class="boring">}
</span></code></pre></pre>
<h4 id="函数签名中的生命周期标注"><a class="header" href="#函数签名中的生命周期标注">函数签名中的生命周期标注</a></h4>
<p>继续之前的 <code>longest</code> 函数,从两个字符串切片中返回较长的那个:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
if x.len() &gt; y.len() {
x
} else {
y
}
}
<span class="boring">}
</span></code></pre></pre>
<p>需要注意的点如下:</p>
<ul>
<li>和泛型一样,使用生命周期参数,需要先声明 <code>&lt;'a&gt;</code></li>
<li><code>x</code><code>y</code> 和返回值至少活得和 <code>'a</code> 一样久(因为返回值要么是 <code>x</code>,要么是 <code>y</code>)</li>
</ul>
<p>该函数签名表明对于某些生命周期 <code>'a</code>,函数的两个参数都至少跟 <code>'a</code> 活得一样久,同时函数的返回引用也至少跟 <code>'a</code> 活得一样久。实际上,这意味着返回值的生命周期与参数生命周期中的较小值一致:虽然两个参数的生命周期都是标注了 <code>'a</code>,但是实际上这两个参数的真实生命周期可能是不一样的(生命周期 <code>'a</code> 不代表生命周期等于 <code>'a</code>,而是大于等于 <code>'a</code>)。</p>
<p>回忆下“鲁迅”说的话,再参考上面的内容,可以得出:<strong>在通过函数签名指定生命周期参数时,我们并没有改变传入引用或者返回引用的真实生命周期,而是告诉编译器当不满足此约束条件时,就拒绝编译通过</strong></p>
<p>因此 <code>longest</code> 函数并不知道 <code>x</code><code>y</code> 具体会活多久,只要知道它们的作用域至少能持续 <code>'a</code> 这么长就行。</p>
<p>当把具体的引用传给 <code>longest</code> 时,那生命周期 <code>'a</code> 的大小就是 <code>x</code><code>y</code> 的作用域的重合部分,换句话说,<code>'a</code> 的大小将等于 <code>x</code><code>y</code> 中较小的那个。由于返回值的生命周期也被标记为 <code>'a</code>,因此返回值的生命周期也是 <code>x</code><code>y</code> 中作用域较小的那个。</p>
<p>说实话,这段文字我写的都快崩溃了,不知道你们读起来如何,实在***太绕了。。那就干脆用一个例子来解释吧:</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let string1 = String::from(&quot;long string is long&quot;);
{
let string2 = String::from(&quot;xyz&quot;);
let result = longest(string1.as_str(), string2.as_str());
println!(&quot;The longest string is {}&quot;, result);
}
}
</code></pre></pre>
<p>在上例中,<code>string1</code> 的作用域直到 <code>main</code> 函数的结束,而 <code>string2</code> 的作用域到内部花括号的结束 <code>}</code>,那么根据之前的理论,<code>'a</code> 是两者中作用域较小的那个,也就是 <code>'a</code> 的生命周期等于 <code>string2</code> 的生命周期,同理,由于函数返回的生命周期也是 '<code>a</code>,可以得出函数返回的生命周期也等于 <code>string2</code> 的生命周期。</p>
<p>现在来验证下上面的结论:<code>result</code> 的生命周期等于参数中生命周期最小的,因此要等于 <code>string2</code> 的生命周期,也就是说,<code>result</code> 要活得和 <code>string2</code> 一样久,观察下代码的实现,可以发现这个结论是正确的!</p>
<p>因此,在这种情况下,通过生命周期标注,编译器得出了和我们肉眼观察一样的结论,而不再是一个蒙圈的大聪明。</p>
<p>再来看一个例子,该例子证明了 <code>result</code> 的生命周期必须等于两个参数中生命周期较小的那个:</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let string1 = String::from(&quot;long string is long&quot;);
let result;
{
let string2 = String::from(&quot;xyz&quot;);
result = longest(string1.as_str(), string2.as_str());
}
println!(&quot;The longest string is {}&quot;, result);
}
</code></pre></pre>
<p>Bang错误冒头了</p>
<pre><code class="language-console">error[E0597]: `string2` does not live long enough
--&gt; src/main.rs:6:44
|
6 | result = longest(string1.as_str(), string2.as_str());
| ^^^^^^^ borrowed value does not live long enough
7 | }
| - `string2` dropped here while still borrowed
8 | println!(&quot;The longest string is {}&quot;, result);
| ------ borrow later used here
</code></pre>
<p>在上述代码中,<code>result</code> 必须要活到 <code>println!</code>处,因为 <code>result</code> 的生命周期是 <code>'a</code>,因此 <code>'a</code> 必须持续到 <code>println!</code></p>
<p><code>longest</code> 函数中,<code>string2</code> 的生命周期也是 <code>'a</code>,由此说明 <code>string2</code> 也必须活到 <code>println!</code> 处,可是 <code>string2</code> 在代码中实际上只能活到内部语句块的花括号处 <code>}</code>,小于它应该具备的生命周期 <code>'a</code>,因此编译出错。</p>
<p>作为人类,我们可以很清晰的看出 <code>result</code> 实际上引用了 <code>string1</code>,因为 <code>string1</code> 的长度明显要比 <code>string2</code> 长,既然如此,编译器不该如此矫情才对,它应该能认识到 <code>result</code> 没有引用 <code>string2</code>,让我们这段代码通过。只能说,作为尊贵的人类,编译器的发明者,你高估了这个工具的能力,它真的做不到!而且 Rust 编译器在调教上是非常保守的:当可能出错也可能不出错时,它会选择前者,抛出编译错误。</p>
<p>总之,显式的使用生命周期,可以让编译器正确的认识到多个引用之间的关系,最终帮我们提前规避可能存在的代码风险。</p>
<p>小练习:尝试着去更改 <code>longest</code> 函数,例如修改参数、生命周期或者返回值,然后推测结果如何,最后再跟编译器的输出进行印证。</p>
<h4 id="深入思考生命周期标注"><a class="header" href="#深入思考生命周期标注">深入思考生命周期标注</a></h4>
<p>使用生命周期的方式往往取决于函数的功能,例如之前的 <code>longest</code> 函数,如果它永远只返回第一个参数 <code>x</code>,生命周期的标注该如何修改(该例子就是上面的小练习结果之一)?</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;str) -&gt; &amp;'a str {
x
}
<span class="boring">}
</span></code></pre></pre>
<p>在此例中,<code>y</code> 完全没有被使用,因此 <code>y</code> 的生命周期与 <code>x</code> 和返回值的生命周期没有任何关系,意味着我们也不必再为 <code>y</code> 标注生命周期,只需要标注 <code>x</code> 参数和返回值即可。</p>
<p><strong>函数的返回值如果是一个引用类型,那么它的生命周期只会来源于</strong></p>
<ul>
<li>函数参数的生命周期</li>
<li>函数体中某个新建引用的生命周期</li>
</ul>
<p>若是后者情况,就是典型的悬垂引用场景:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn longest&lt;'a&gt;(x: &amp;str, y: &amp;str) -&gt; &amp;'a str {
let result = String::from(&quot;really long string&quot;);
result.as_str()
}
<span class="boring">}
</span></code></pre></pre>
<p>上面的函数的返回值就和参数 <code>x</code><code>y</code> 没有任何关系,而是引用了函数体内创建的字符串,那么很显然,该函数会报错:</p>
<pre><code class="language-console">error[E0515]: cannot return value referencing local variable `result` // 返回值result引用了本地的变量
--&gt; src/main.rs:11:5
|
11 | result.as_str()
| ------^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `result` is borrowed here
</code></pre>
<p>主要问题就在于,<code>result</code> 在函数结束后就被释放,但是在函数结束后,对 <code>result</code> 的引用依然在继续。在这种情况下,没有办法指定合适的生命周期来让编译通过,因此我们也就在 Rust 中避免了悬垂引用。</p>
<p>那遇到这种情况该怎么办?最好的办法就是返回内部字符串的所有权,然后把字符串的所有权转移给调用者:</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn longest&lt;'a&gt;(_x: &amp;str, _y: &amp;str) -&gt; String {
String::from(&quot;really long string&quot;)
}
fn main() {
let s = longest(&quot;not&quot;, &quot;important&quot;);
}
</code></pre></pre>
<p>至此可以对生命周期进行下总结生命周期语法用来将函数的多个引用参数和返回值的作用域关联到一起一旦关联到一起后Rust 就拥有充分的信息来确保我们的操作是内存安全的。</p>
<h2 id="结构体中的生命周期"><a class="header" href="#结构体中的生命周期">结构体中的生命周期</a></h2>
<p>不仅仅函数具有生命周期,结构体其实也有这个概念,只不过我们之前对结构体的使用都停留在非引用类型字段上。细心的同学应该能回想起来,之前为什么不在结构体中使用字符串字面量或者字符串切片,而是统一使用 <code>String</code> 类型?原因很简单,后者在结构体初始化时,只要转移所有权即可,而前者,抱歉,它们是引用,它们不能为所欲为。</p>
<p>既然之前已经理解了生命周期,那么意味着在结构体中使用引用也变得可能:只要为结构体中的<strong>每一个引用标注上生命周期</strong>即可:</p>
<pre><pre class="playground"><code class="language-rust edition2021">struct ImportantExcerpt&lt;'a&gt; {
part: &amp;'a str,
}
fn main() {
let novel = String::from(&quot;Call me Ishmael. Some years ago...&quot;);
let first_sentence = novel.split('.').next().expect(&quot;Could not find a '.'&quot;);
let i = ImportantExcerpt {
part: first_sentence,
};
}
</code></pre></pre>
<p><code>ImportantExcerpt</code> 结构体中有一个引用类型的字段 <code>part</code>,因此需要为它标注上生命周期。结构体的生命周期标注语法跟泛型参数语法很像,需要对生命周期参数进行声明 <code>&lt;'a&gt;</code>。该生命周期标注说明,<strong>结构体 <code>ImportantExcerpt</code> 所引用的字符串 <code>str</code> 必须比该结构体活得更久</strong></p>
<p><code>main</code> 函数实现来看,<code>ImportantExcerpt</code> 的生命周期从第 4 行开始,到 <code>main</code> 函数末尾结束,而该结构体引用的字符串从第一行开始,也是到 <code>main</code> 函数末尾结束,可以得出结论<strong>结构体引用的字符串活得比结构体久</strong>,这符合了编译器对生命周期的要求,因此编译通过。</p>
<p>与之相反,下面的代码就无法通过编译:</p>
<pre><pre class="playground"><code class="language-rust edition2021">#[derive(Debug)]
struct ImportantExcerpt&lt;'a&gt; {
part: &amp;'a str,
}
fn main() {
let i;
{
let novel = String::from(&quot;Call me Ishmael. Some years ago...&quot;);
let first_sentence = novel.split('.').next().expect(&quot;Could not find a '.'&quot;);
i = ImportantExcerpt {
part: first_sentence,
};
}
println!(&quot;{:?}&quot;,i);
}
</code></pre></pre>
<p>观察代码,<strong>可以看出结构体比它引用的字符串活得更久</strong>,引用字符串在内部语句块末尾 <code>}</code> 被释放后,<code>println!</code> 依然在外面使用了该结构体,因此会导致无效的引用,不出所料,编译报错:</p>
<pre><code class="language-console">error[E0597]: `novel` does not live long enough
--&gt; src/main.rs:10:30
|
10 | let first_sentence = novel.split('.').next().expect(&quot;Could not find a '.'&quot;);
| ^^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
14 | }
| - `novel` dropped here while still borrowed
15 | println!(&quot;{:?}&quot;,i);
| - borrow later used here
</code></pre>
<h2 id="生命周期消除"><a class="header" href="#生命周期消除">生命周期消除</a></h2>
<p>实际上,对于编译器来说,每一个引用类型都有一个生命周期,那么为什么我们在使用过程中,很多时候无需标注生命周期?例如:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn first_word(s: &amp;str) -&gt; &amp;str {
let bytes = s.as_bytes();
for (i, &amp;item) in bytes.iter().enumerate() {
if item == b' ' {
return &amp;s[0..i];
}
}
&amp;s[..]
}
<span class="boring">}
</span></code></pre></pre>
<p>该函数的参数和返回值都是引用类型,尽管我们没有显式的为其标注生命周期,编译依然可以通过。其实原因不复杂,<strong>编译器为了简化用户的使用,运用了生命周期消除大法</strong></p>
<p>对于 <code>first_word</code> 函数,它的返回值是一个引用类型,那么该引用只有两种情况:</p>
<ul>
<li>从参数获取</li>
<li>从函数体内部新创建的变量获取</li>
</ul>
<p>如果是后者,就会出现悬垂引用,最终被编译器拒绝,因此只剩一种情况:返回值的引用是获取自参数,这就意味着参数和返回值的生命周期是一样的。道理很简单,我们能看出来,编译器自然也能看出来,因此,就算我们不标注生命周期,也不会产生歧义。</p>
<p>实际上,在 Rust 1.0 版本之前,这种代码果断不给通过,因为 Rust 要求必须显式的为所有引用标注生命周期:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;'a str {
<span class="boring">}
</span></code></pre></pre>
<p>在写了大量的类似代码后Rust 社区抱怨声四起,包括开发者自己都忍不了了,最终揭锅而起,这才有了我们今日的幸福。</p>
<p>生命周期消除的规则不是一蹴而就,而是伴随着 <code>总结-改善</code> 流程的周而复始一步一步走到今天这也意味着该规则以后可能也会进一步增加我们需要手动标注生命周期的时候也会越来越少hooray!</p>
<p>在开始之前有几点需要注意:</p>
<ul>
<li>消除规则不是万能的,若编译器不能确定某件事是正确时,会直接判为不正确,那么你还是需要手动标注生命周期</li>
<li><strong>函数或者方法中,参数的生命周期被称为 <code>输入生命周期</code>,返回值的生命周期被称为 <code>输出生命周期</code></strong></li>
</ul>
<h4 id="三条消除规则"><a class="header" href="#三条消除规则">三条消除规则</a></h4>
<p>编译器使用三条消除规则来确定哪些场景不需要显式地去标注生命周期。其中第一条规则应用在输入生命周期上,第二、三条应用在输出生命周期上。若编译器发现三条规则都不适用时,就会报错,提示你需要手动标注生命周期。</p>
<ol>
<li>
<p><strong>每一个引用参数都会获得独自的生命周期</strong></p>
<p>例如一个引用参数的函数就有一个生命周期标注: <code>fn foo&lt;'a&gt;(x: &amp;'a i32)</code>,两个引用参数的有两个生命周期标注:<code>fn foo&lt;'a, 'b&gt;(x: &amp;'a i32, y: &amp;'b i32)</code>, 依此类推。</p>
</li>
<li>
<p><strong>若只有一个输入生命周期(函数参数中只有一个引用类型),那么该生命周期会被赋给所有的输出生命周期</strong>,也就是所有返回值的生命周期都等于该输入生命周期</p>
<p>例如函数 <code>fn foo(x: &amp;i32) -&gt; &amp;i32</code><code>x</code> 参数的生命周期会被自动赋给返回值 <code>&amp;i32</code>,因此该函数等同于 <code>fn foo&lt;'a&gt;(x: &amp;'a i32) -&gt; &amp;'a i32</code></p>
</li>
<li>
<p><strong>若存在多个输入生命周期,且其中一个是 <code>&amp;self</code><code>&amp;mut self</code>,则 <code>&amp;self</code> 的生命周期被赋给所有的输出生命周期</strong></p>
<p>拥有 <code>&amp;self</code> 形式的参数,说明该函数是一个 <code>方法</code>,该规则让方法的使用便利度大幅提升。</p>
</li>
</ol>
<p>规则其实很好理解,但是,爱思考的读者肯定要发问了,例如第三条规则,若一个方法,它的返回值的生命周期就是跟参数 <code>&amp;self</code> 的不一样怎么办?总不能强迫我返回的值总是和 <code>&amp;self</code> 活得一样久吧?! 问得好,答案很简单:手动标注生命周期,因为这些规则只是编译器发现你没有标注生命周期时默认去使用的,当你标注生命周期后,编译器自然会乖乖听你的话。</p>
<p>让我们假装自己是编译器,然后看下以下的函数该如何应用这些规则:</p>
<p><strong>例子 1</strong></p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn first_word(s: &amp;str) -&gt; &amp;str { // 实际项目中的手写代码
<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 first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;str { // 编译器自动为参数添加生命周期
<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 first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;'a str { // 编译器自动为返回值添加生命周期
<span class="boring">}
</span></code></pre></pre>
<p>此时,编译器为函数签名中的所有引用都自动添加了具体的生命周期,因此编译通过,且用户无需手动去标注生命周期,只要按照 <code>fn first_word(s: &amp;str) -&gt; &amp;str { </code> 的形式写代码即可。</p>
<p><strong>例子 2</strong>
再来看一个例子:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str { // 实际项目中的手写代码
<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 longest&lt;'a, 'b&gt;(x: &amp;'a str, y: &amp;'b str) -&gt; &amp;str {
<span class="boring">}
</span></code></pre></pre>
<p>但是此时,第二条规则却无法被使用,因为输入生命周期有两个,第三条规则也不符合,因为它是函数,不是方法,因此没有 <code>&amp;self</code> 参数。在套用所有规则后,编译器依然无法为返回值标注合适的生命周期,因此,编译器就会报错,提示我们需要手动标注生命周期:</p>
<pre><code class="language-console">error[E0106]: missing lifetime specifier
--&gt; src/main.rs:1:47
|
1 | fn longest&lt;'a, 'b&gt;(x: &amp;'a str, y: &amp;'b str) -&gt; &amp;str {
| ------- ------- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
note: these named lifetimes are available to use
--&gt; src/main.rs:1:12
|
1 | fn longest&lt;'a, 'b&gt;(x: &amp;'a str, y: &amp;'b str) -&gt; &amp;str {
| ^^ ^^
help: consider using one of the available lifetimes here
|
1 | fn longest&lt;'a, 'b&gt;(x: &amp;'a str, y: &amp;'b str) -&gt; &amp;'lifetime str {
| +++++++++
</code></pre>
<p>不得不说Rust 编译器真的很强大,还贴心的给我们提示了该如何修改,虽然。。。好像。。。。它的提示貌似不太准确。这里我们更希望参数和返回值都是 <code>'a</code> 生命周期。</p>
<h2 id="方法中的生命周期"><a class="header" href="#方法中的生命周期">方法中的生命周期</a></h2>
<p>先来回忆下泛型的语法:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct Point&lt;T&gt; {
x: T,
y: T,
}
impl&lt;T&gt; Point&lt;T&gt; {
fn x(&amp;self) -&gt; &amp;T {
&amp;self.x
}
}
<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>struct ImportantExcerpt&lt;'a&gt; {
part: &amp;'a str,
}
impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
fn level(&amp;self) -&gt; i32 {
3
}
}
<span class="boring">}
</span></code></pre></pre>
<p>其中有几点需要注意的:</p>
<ul>
<li><code>impl</code> 中必须使用结构体的完整名称,包括 <code>&lt;'a&gt;</code>,因为<em>生命周期标注也是结构体类型的一部分</em></li>
<li>方法签名中,往往不需要标注生命周期,得益于生命周期消除的第一和第三规则</li>
</ul>
<p>下面的例子展示了第三规则应用的场景:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
fn announce_and_return_part(&amp;self, announcement: &amp;str) -&gt; &amp;str {
println!(&quot;Attention please: {}&quot;, announcement);
self.part
}
}
<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>impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
fn announce_and_return_part&lt;'b&gt;(&amp;'a self, announcement: &amp;'b str) -&gt; &amp;str {
println!(&quot;Attention please: {}&quot;, announcement);
self.part
}
}
<span class="boring">}
</span></code></pre></pre>
<p>需要注意的是,编译器不知道 <code>announcement</code> 的生命周期到底多长,因此它无法简单的给予它生命周期 <code>'a</code>,而是重新声明了一个全新的生命周期 <code>'b</code></p>
<p>接着,编译器应用第三规则,将 <code>&amp;self</code> 的生命周期赋给返回值 <code>&amp;str</code></p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
fn announce_and_return_part&lt;'b&gt;(&amp;'a self, announcement: &amp;'b str) -&gt; &amp;'a str {
println!(&quot;Attention please: {}&quot;, announcement);
self.part
}
}
<span class="boring">}
</span></code></pre></pre>
<p>Bingo最开始的代码尽管我们没有给方法标注生命周期但是在第一和第三规则的配合下编译器依然完美的为我们亮起了绿灯。</p>
<p>在结束这块儿内容之前,再来做一个有趣的修改,将方法返回的生命周期改为<code>'b</code></p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
fn announce_and_return_part&lt;'b&gt;(&amp;'a self, announcement: &amp;'b str) -&gt; &amp;'b str {
println!(&quot;Attention please: {}&quot;, announcement);
self.part
}
}
<span class="boring">}
</span></code></pre></pre>
<p>此时,编译器会报错,因为编译器无法知道 <code>'a</code><code>'b</code> 的关系。 <code>&amp;self</code> 生命周期是 <code>'a</code>,那么 <code>self.part</code> 的生命周期也是 <code>'a</code>,但是好巧不巧的是,我们手动为返回值 <code>self.part</code> 标注了生命周期 <code>'b</code>,因此编译器需要知道 <code>'a</code><code>'b</code> 的关系。</p>
<p>有一点很容易推理出来:由于 <code>&amp;'a self</code> 是被引用的一方,因此引用它的 <code>&amp;'b str</code> 必须要活得比它短,否则会出现悬垂引用。因此说明生命周期 <code>'b</code> 必须要比 <code>'a</code> 小,只要满足了这一点,编译器就不会再报错:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;'a: 'b, 'b&gt; ImportantExcerpt&lt;'a&gt; {
fn announce_and_return_part(&amp;'a self, announcement: &amp;'b str) -&gt; &amp;'b str {
println!(&quot;Attention please: {}&quot;, announcement);
self.part
}
}
<span class="boring">}
</span></code></pre></pre>
<p>Bang一个复杂的玩意儿被甩到了你面前就问怕不怕</p>
<p>就关键点稍微解释下:</p>
<ul>
<li><code>'a: 'b</code>,是生命周期约束语法,跟泛型约束非常相似,用于说明 <code>'a</code> 必须比 <code>'b</code> 活得久</li>
<li>可以把 <code>'a</code><code>'b</code> 都在同一个地方声明(如上),或者分开声明但通过 <code>where 'a: 'b</code> 约束生命周期关系,如下:</li>
</ul>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
fn announce_and_return_part&lt;'b&gt;(&amp;'a self, announcement: &amp;'b str) -&gt; &amp;'b str
where
'a: 'b,
{
println!(&quot;Attention please: {}&quot;, announcement);
self.part
}
}
<span class="boring">}
</span></code></pre></pre>
<p>总之,实现方法比想象中简单:加一个约束,就能暗示编译器,尽管引用吧,反正我想引用的内容比我活得久,爱咋咋地,我怎么都不会引用到无效的内容!</p>
<h2 id="静态生命周期"><a class="header" href="#静态生命周期">静态生命周期</a></h2>
<p>在 Rust 中有一个非常特殊的生命周期,那就是 <code>'static</code>,拥有该生命周期的引用可以和整个程序活得一样久。</p>
<p>在之前我们学过字符串字面量,提到过它是被硬编码进 Rust 的二进制文件中,因此这些字符串变量全部具有 <code>'static</code> 的生命周期:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s: &amp;'static str = &quot;我没啥优点,就是活得久,嘿嘿&quot;;
<span class="boring">}
</span></code></pre></pre>
<p>这时候,有些聪明的小脑瓜就开始开动了:当生命周期不知道怎么标时,对类型施加一个静态生命周期的约束 <code>T: 'static</code> 是不是很爽?这样我和编译器再也不用操心它到底活多久了。</p>
<p>嗯,只能说,这个想法是对的,在不少情况下,<code>'static</code> 约束确实可以解决生命周期编译不通过的问题,但是问题来了:本来该引用没有活那么久,但是你非要说它活那么久,万一引入了潜在的 BUG 怎么办?</p>
<p>因此,遇到因为生命周期导致的编译不通过问题,首先想的应该是:是否是我们试图创建一个悬垂引用,或者是试图匹配不一致的生命周期,而不是简单粗暴的用 <code>'static</code> 来解决问题。</p>
<p>但是,话说回来,存在即合理,有时候,<code>'static</code> 确实可以帮助我们解决非常复杂的生命周期问题甚至是无法被手动解决的生命周期问题,那么此时就应该放心大胆的用,只要你确定:<strong>你的所有引用的生命周期都是正确的,只是编译器太笨不懂罢了</strong></p>
<p>总结下:</p>
<ul>
<li>生命周期 <code>'static</code> 意味着能和程序活得一样久,例如字符串字面量和特征对象</li>
<li>实在遇到解决不了的生命周期标注问题,可以尝试 <code>T: 'static</code>,有时候它会给你奇迹</li>
</ul>
<blockquote>
<p>事实上,关于 <code>'static</code>, 有两种用法: <code>&amp;'static</code><code>T: 'static</code>,详细内容请参见<a href="https://course.rs/advance/lifetime/static.html">此处</a></p>
</blockquote>
<h2 id="一个复杂例子-泛型特征约束"><a class="header" href="#一个复杂例子-泛型特征约束">一个复杂例子: 泛型、特征约束</a></h2>
<p>手指已经疲软无力,我好想停止,但是华丽的开场都要有与之匹配的谢幕,那我们就用一个稍微复杂点的例子来结束:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::fmt::Display;
fn longest_with_an_announcement&lt;'a, T&gt;(
x: &amp;'a str,
y: &amp;'a str,
ann: T,
) -&gt; &amp;'a str
where
T: Display,
{
println!(&quot;Announcement! {}&quot;, ann);
if x.len() &gt; y.len() {
x
} else {
y
}
}
<span class="boring">}
</span></code></pre></pre>
<p>依然是熟悉的配方 <code>longest</code>,但是多了一段废话: <code>ann</code>,因为要用格式化 <code>{}</code> 来输出 <code>ann</code>,因此需要它实现 <code>Display</code> 特征。</p>
<h2 id="课后练习"><a class="header" href="#课后练习">课后练习</a></h2>
<blockquote>
<p><a href="https://zh.practice.rs/lifetime/basic.html">Rust By Practice</a>,支持代码在线编辑和运行,并提供详细的习题解答。(本节暂无习题解答)</p>
</blockquote>
<h2 id="总结"><a class="header" href="#总结">总结</a></h2>
<p>我不知道支撑我一口气写完的勇气是什么,也许是不做完不爽夫斯基,也许是一些读者对本书的期待,不管如何,这章足足写了 17000 字,可惜不是写小说,不然肯定可以获取很多月票 :)</p>
<p>从本章开始,最大的收获就是可以在结构体中使用引用类型了,说实话,为了引入这个特性,我已经憋了足足 N 个章节……</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/collections/hashmap.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="../basic/result-error/intro.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/collections/hashmap.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="../basic/result-error/intro.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 = "basic/lifetime.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>