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

777 lines
66 KiB

9 months ago
<!DOCTYPE HTML>
<html lang="zh-CN" class="light sidebar-visible" 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-de23e50b.svg">
<link rel="shortcut icon" href="../favicon-8114d1fc.png">
<link rel="stylesheet" href="../css/variables-8adf115d.css">
<link rel="stylesheet" href="../css/general-2459343d.css">
<link rel="stylesheet" href="../css/chrome-ae938929.css">
<link rel="stylesheet" href="../css/print-9e4910d8.css" media="print">
9 months ago
<!-- Fonts -->
<link rel="stylesheet" href="../fonts/fonts-9644e21d.css">
9 months ago
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" id="mdbook-highlight-css" href="../highlight-493f70e1.css">
<link rel="stylesheet" id="mdbook-tomorrow-night-css" href="../tomorrow-night-4c0ae647.css">
<link rel="stylesheet" id="mdbook-ayu-highlight-css" href="../ayu-highlight-3fdfc3ac.css">
9 months ago
<!-- Custom theme stylesheets -->
<link rel="stylesheet" href="../theme/style-78591068.css">
9 months ago
<!-- Provide site root and default themes to javascript -->
<script>
const path_to_root = "../";
const default_light_theme = "light";
const default_dark_theme = "navy";
window.path_to_searchindex_js = "../searchindex-4a1a74fa.js";
9 months ago
</script>
<!-- Start loading toc.js asap -->
<script src="../toc-42887675.js"></script>
9 months ago
</head>
<body>
<div id="mdbook-help-container">
<div id="mdbook-help-popup">
<h2 class="mdbook-help-title">Keyboard shortcuts</h2>
<div>
<p>Press <kbd></kbd> or <kbd></kbd> to navigate between chapters</p>
<p>Press <kbd>S</kbd> or <kbd>/</kbd> to search in the book</p>
<p>Press <kbd>?</kbd> to show this help</p>
<p>Press <kbd>Esc</kbd> to hide this help</p>
</div>
</div>
</div>
<div id="mdbook-body-container">
9 months ago
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
let theme = localStorage.getItem('mdbook-theme');
let 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>
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
let theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
const html = document.documentElement;
html.classList.remove('light')
html.classList.add(theme);
html.classList.add("js");
</script>
<input type="checkbox" id="mdbook-sidebar-toggle-anchor" class="hidden">
9 months ago
<!-- Hide / unhide sidebar before it is displayed -->
<script>
let sidebar = null;
const sidebar_toggle = document.getElementById("mdbook-sidebar-toggle-anchor");
9 months ago
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
sidebar_toggle.checked = false;
}
if (sidebar === 'visible') {
sidebar_toggle.checked = true;
} else {
html.classList.remove('sidebar-visible');
9 months ago
}
</script>
<nav id="mdbook-sidebar" class="sidebar" aria-label="Table of contents">
9 months ago
<!-- populated by js -->
<mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
<noscript>
<iframe class="sidebar-iframe-outer" src="../toc.html"></iframe>
</noscript>
<div id="mdbook-sidebar-resize-handle" class="sidebar-resize-handle">
9 months ago
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<div id="mdbook-page-wrapper" class="page-wrapper">
9 months ago
<div class="page">
<div id="mdbook-menu-bar-hover-placeholder"></div>
<div id="mdbook-menu-bar" class="menu-bar sticky">
9 months ago
<div class="left-buttons">
<label id="mdbook-sidebar-toggle" class="icon-button" for="mdbook-sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="mdbook-sidebar">
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M0 96C0 78.3 14.3 64 32 64H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 128 0 113.7 0 96zM0 256c0-17.7 14.3-32 32-32H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32c-17.7 0-32-14.3-32-32zM448 416c0 17.7-14.3 32-32 32H32c-17.7 0-32-14.3-32-32s14.3-32 32-32H416c17.7 0 32 14.3 32 32z"/></svg></span>
9 months ago
</label>
<button id="mdbook-theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="mdbook-theme-list">
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M371.3 367.1c27.3-3.9 51.9-19.4 67.2-42.9L600.2 74.1c12.6-19.5 9.4-45.3-7.6-61.2S549.7-4.4 531.1 9.6L294.4 187.2c-24 18-38.2 46.1-38.4 76.1L371.3 367.1zm-19.6 25.4l-116-104.4C175.9 290.3 128 339.6 128 400c0 3.9 .2 7.8 .6 11.6c1.8 17.5-10.2 36.4-27.8 36.4H96c-17.7 0-32 14.3-32 32s14.3 32 32 32H240c61.9 0 112-50.1 112-112c0-2.5-.1-5-.2-7.5z"/></svg></span>
9 months ago
</button>
<ul id="mdbook-theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-default_theme">Auto</button></li>
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-ayu">Ayu</button></li>
9 months ago
</ul>
<button id="mdbook-search-toggle" class="icon-button" type="button" title="Search (`/`)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="/ s" aria-controls="mdbook-searchbar">
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M416 208c0 45.9-14.9 88.3-40 122.7L502.6 457.4c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L330.7 376c-34.4 25.2-76.8 40-122.7 40C93.1 416 0 322.9 0 208S93.1 0 208 0S416 93.1 416 208zM208 352c79.5 0 144-64.5 144-144s-64.5-144-144-144S64 128.5 64 208s64.5 144 144 144z"/></svg></span>
9 months ago
</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">
<span class=fa-svg id="print-button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M128 0C92.7 0 64 28.7 64 64v96h64V64H354.7L384 93.3V160h64V93.3c0-17-6.7-33.3-18.7-45.3L400 18.7C388 6.7 371.7 0 354.7 0H128zM384 352v32 64H128V384 368 352H384zm64 32h32c17.7 0 32-14.3 32-32V256c0-35.3-28.7-64-64-64H64c-35.3 0-64 28.7-64 64v96c0 17.7 14.3 32 32 32H64v64c0 35.3 28.7 64 64 64H384c35.3 0 64-28.7 64-64V384zm-16-88c-13.3 0-24-10.7-24-24s10.7-24 24-24s24 10.7 24 24s-10.7 24-24 24z"/></svg></span>
9 months ago
</a>
<a href="https://github.com/sunface/rust-course" title="Git repository" aria-label="Git repository">
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span>
9 months ago
</a>
<a href="https://github.com/sunface/rust-course/edit/main/src/basic/lifetime.md" title="Suggest an edit" aria-label="Suggest an edit" rel="edit">
<span class=fa-svg id="git-edit-button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M421.7 220.3l-11.3 11.3-22.6 22.6-205 205c-6.6 6.6-14.8 11.5-23.8 14.1L30.8 511c-8.4 2.5-17.5 .2-23.7-6.1S-1.5 489.7 1 481.2L38.7 353.1c2.6-9 7.5-17.2 14.1-23.8l205-205 22.6-22.6 11.3-11.3 33.9 33.9 62.1 62.1 33.9 33.9zM96 353.9l-9.3 9.3c-.9 .9-1.6 2.1-2 3.4l-25.3 86 86-25.3c1.3-.4 2.5-1.1 3.4-2l9.3-9.3H112c-8.8 0-16-7.2-16-16V353.9zM453.3 19.3l39.4 39.4c25 25 25 65.5 0 90.5l-14.5 14.5-22.6 22.6-11.3 11.3-33.9-33.9-62.1-62.1L314.3 67.7l11.3-11.3 22.6-22.6 14.5-14.5c25-25 65.5-25 90.5 0z"/></svg></span>
9 months ago
</a>
</div>
</div>
<div id="mdbook-search-wrapper" class="hidden">
<form id="mdbook-searchbar-outer" class="searchbar-outer">
<div class="search-wrapper">
<input type="search" id="mdbook-searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="mdbook-searchresults-outer" aria-describedby="searchresults-header">
<div class="spinner-wrapper">
<span class=fa-svg id="fa-spin"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M304 48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zm0 416c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM48 304c26.5 0 48-21.5 48-48s-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48zm464-48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM142.9 437c18.7-18.7 18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zm0-294.2c18.7-18.7 18.7-49.1 0-67.9S93.7 56.2 75 75s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zM369.1 437c18.7 18.7 49.1 18.7 67.9 0s18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9z"/></svg></span>
</div>
</div>
9 months ago
</form>
<div id="mdbook-searchresults-outer" class="searchresults-outer hidden">
<div id="mdbook-searchresults-header" class="searchresults-header"></div>
<ul id="mdbook-searchresults">
9 months ago
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('mdbook-sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('mdbook-sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#mdbook-sidebar a')).forEach(function(link) {
9 months ago
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="mdbook-content" class="content">
9 months ago
<main>
<h1 id="认识生命周期"><a class="header" href="#认识生命周期">认识生命周期</a></h1>
<p>各位读者,之前的集合章节挺简单吧?是不是安逸了挺久了?要不咱们加点料?来试试 Rust 中令人闻风丧胆的生命周期?</p>
<p>生命周期,简而言之就是引用的有效作用域。在大多数时候,我们无需手动声明生命周期,因为编译器可以自动进行推导,用类型来类比下:</p>
9 months ago
<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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</span><span class="boring">fn main() {
</span>{
let r;
{
let x = 5;
r = &amp;x;
}
println!("r: {}", r);
}
<span class="boring">}</span></code></pre>
9 months ago
<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!("r: {}", 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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</span><span class="boring">fn main() {
</span>{
let r; // ---------+-- 'a
// |
{ // |
let x = 5; // -+-- 'b |
r = &amp;x; // | |
} // -+ |
// |
println!("r: {}", r); // |
} // ---------+
<span class="boring">}</span></code></pre>
9 months ago
<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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</span><span class="boring">fn main() {
</span>{
let x = 5; // ----------+-- 'b
// |
let r = &amp;x; // --+-- 'a |
// | |
println!("r: {}", r); // | |
// --+ |
} // ----------+
<span class="boring">}</span></code></pre>
9 months ago
<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 class="playground"><code class="language-rust edition2021">fn main() {
9 months ago
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {}", result);
}
fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
if x.len() &gt; y.len() {
x
} else {
y
}
}</code></pre>
9 months ago
<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>
9 months ago
<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>
9 months ago
</blockquote>
<p>鲁迅说过的话,总是值得重点关注,当你未来更加理解生命周期时,你才会发现这句话的精髓和重要!现在先简单记住,<strong>标记的生命周期只是为了取悦编译器,让编译器不要难为我们</strong>,记住了吗?没记住,再回头看一遍,这对未来你遇到生命周期问题时会有很大的帮助!</p>
9 months ago
<p>在很多时候编译器是很聪明的,但是总有些时候,它会化身大聪明,自以为什么都很懂,然后去拒绝我们代码的执行,此时,就需要我们通过生命周期标注来告诉这个大聪明:别自作聪明了,听我的就好。</p>
<p>例如一个变量,只能活一个花括号,那么就算你给它标注一个活全局的生命周期,它还是会在前面的花括号结束处被释放掉,并不会真的全局存活。</p>
<p>生命周期的语法也颇为与众不同,以 <code>'</code> 开头,名称往往是一个单独的小写字母,大多数人都用 <code>'a</code> 来作为生命周期的名称。 如果是引用类型的参数,那么生命周期会位于引用符号 <code>&amp;</code> 之后,并用一个空格来将生命周期和引用参数分隔开:</p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</span><span class="boring">fn main() {
</span>&amp;i32 // 一个引用
&amp;'a i32 // 具有显式生命周期的引用
&amp;'a mut i32 // 具有显式生命周期的可变引用
<span class="boring">}</span></code></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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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>
9 months ago
<h4 id="函数签名中的生命周期标注"><a class="header" href="#函数签名中的生命周期标注">函数签名中的生命周期标注</a></h4>
<p>继续之前的 <code>longest</code> 函数,从两个字符串切片中返回较长的那个:</p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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>
9 months ago
<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 class="playground"><code class="language-rust edition2021">fn main() {
9 months ago
let string1 = String::from("long string is long");
{
let string2 = String::from("xyz");
let result = longest(string1.as_str(), string2.as_str());
println!("The longest string is {}", result);
}
}</code></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>
9 months ago
<p>现在来验证下上面的结论:<code>result</code> 的生命周期等于参数中生命周期最小的,因此要等于 <code>string2</code> 的生命周期,也就是说,<code>result</code> 要活得和 <code>string2</code> 一样久,观察下代码的实现,可以发现这个结论是正确的!</p>
<p>因此,在这种情况下,通过生命周期标注,编译器得出了和我们肉眼观察一样的结论,而不再是一个蒙圈的大聪明。</p>
<p>再来看一个例子,该例子证明了 <code>result</code> 的生命周期必须等于两个参数中生命周期较小的那个:</p>
<pre class="playground"><code class="language-rust edition2021">fn main() {
9 months ago
let string1 = String::from("long string is long");
let result;
{
let string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str());
}
println!("The longest string is {}", result);
}</code></pre>
9 months ago
<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!("The longest string is {}", 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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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>
9 months ago
<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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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("really long string");
result.as_str()
}
<span class="boring">}</span></code></pre>
9 months ago
<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 class="playground"><code class="language-rust edition2021">fn longest(_x: &amp;str, _y: &amp;str) -&gt; String {
9 months ago
String::from("really long string")
}
fn main() {
let s = longest("not", "important");
}</code></pre>
9 months ago
<p>至此可以对生命周期进行下总结生命周期语法用来将函数的多个引用参数和返回值的作用域关联到一起一旦关联到一起后Rust 就拥有充分的信息来确保我们的操作是内存安全的。</p>
<h2 id="结构体中的生命周期"><a class="header" href="#结构体中的生命周期">结构体中的生命周期</a></h2>
<p>不仅仅函数具有生命周期,结构体其实也有这个概念,只不过我们之前对结构体的使用都停留在非引用类型字段上。细心的同学应该能回想起来,之前为什么不在结构体中使用字符串字面量或者字符串切片,而是统一使用 <code>String</code> 类型?原因很简单,后者在结构体初始化时,只要转移所有权即可,而前者,抱歉,它们是引用,它们不能为所欲为。</p>
<p>既然之前已经理解了生命周期,那么意味着在结构体中使用引用也变得可能:只要为结构体中的<strong>每一个引用标注上生命周期</strong>即可:</p>
<pre class="playground"><code class="language-rust edition2021">struct ImportantExcerpt&lt;'a&gt; {
9 months ago
part: &amp;'a str,
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().expect("Could not find a '.'");
let i = ImportantExcerpt {
part: first_sentence,
};
}</code></pre>
9 months ago
<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 class="playground"><code class="language-rust edition2021">#[derive(Debug)]
9 months ago
struct ImportantExcerpt&lt;'a&gt; {
part: &amp;'a str,
}
fn main() {
let i;
{
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().expect("Could not find a '.'");
i = ImportantExcerpt {
part: first_sentence,
};
}
println!("{:?}",i);
}</code></pre>
9 months ago
<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("Could not find a '.'");
| ^^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
14 | }
| - `novel` dropped here while still borrowed
15 | println!("{:?}",i);
| - borrow later used here
</code></pre>
<h2 id="生命周期消除"><a class="header" href="#生命周期消除">生命周期消除</a></h2>
<p>实际上,对于编译器来说,每一个引用类型都有一个生命周期,那么为什么我们在使用过程中,很多时候无需标注生命周期?例如:</p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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>
9 months ago
<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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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>
9 months ago
<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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</span><span class="boring">fn main() {
</span>fn first_word(s: &amp;str) -&gt; &amp;str { // 实际项目中的手写代码
<span class="boring">}</span></code></pre>
9 months ago
<p>首先,我们手写的代码如上所示时,编译器会先应用第一条规则,为每个参数标注一个生命周期:</p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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>
9 months ago
<p>此时,第二条规则就可以进行应用,因为函数只有一个输入生命周期,因此该生命周期会被赋予所有的输出生命周期:</p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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>
9 months ago
<p>此时,编译器为函数签名中的所有引用都自动添加了具体的生命周期,因此编译通过,且用户无需手动去标注生命周期,只要按照 <code>fn first_word(s: &amp;str) -&gt; &amp;str { </code> 的形式写代码即可。</p>
<p><strong>例子 2</strong>
再来看一个例子:</p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</span><span class="boring">fn main() {
</span>fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str { // 实际项目中的手写代码
<span class="boring">}</span></code></pre>
9 months ago
<p>首先,编译器会应用第一条规则,为每个参数都标注生命周期:</p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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>
9 months ago
<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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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>
9 months ago
<p>实际上,为具有生命周期的结构体实现方法时,我们使用的语法跟泛型参数语法很相似:</p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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>
9 months ago
<p>其中有几点需要注意的:</p>
<ul>
<li><code>impl</code> 中必须使用结构体的完整名称,包括 <code>&lt;'a&gt;</code>,因为<em>生命周期标注也是结构体类型的一部分</em></li>
<li>方法签名中,往往不需要标注生命周期,得益于生命周期消除的第一和第三规则</li>
</ul>
<p>下面的例子展示了第三规则应用的场景:</p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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!("Attention please: {}", announcement);
self.part
}
}
<span class="boring">}</span></code></pre>
9 months ago
<p>首先,编译器应用第一规则,给予每个输入参数一个生命周期:</p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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!("Attention please: {}", announcement);
self.part
}
}
<span class="boring">}</span></code></pre>
9 months ago
<p>需要注意的是,编译器不知道 <code>announcement</code> 的生命周期到底多长,因此它无法简单的给予它生命周期 <code>'a</code>,而是重新声明了一个全新的生命周期 <code>'b</code></p>
<p>接着,编译器应用第三规则,将 <code>&amp;self</code> 的生命周期赋给返回值 <code>&amp;str</code></p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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!("Attention please: {}", announcement);
self.part
}
}
<span class="boring">}</span></code></pre>
9 months ago
<p>Bingo最开始的代码尽管我们没有给方法标注生命周期但是在第一和第三规则的配合下编译器依然完美的为我们亮起了绿灯。</p>
<p>在结束这块儿内容之前,再来做一个有趣的修改,将方法返回的生命周期改为<code>'b</code></p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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!("Attention please: {}", announcement);
self.part
}
}
<span class="boring">}</span></code></pre>
9 months ago
<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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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!("Attention please: {}", announcement);
self.part
}
}
<span class="boring">}</span></code></pre>
9 months ago
<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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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!("Attention please: {}", announcement);
self.part
}
}
<span class="boring">}</span></code></pre>
9 months ago
<p>总之,实现方法比想象中简单:加一个约束,就能暗示编译器,尽管引用吧,反正我想引用的内容比我活得久,爱咋咋地,我怎么都不会引用到无效的内容!</p>
<h2 id="静态生命周期"><a class="header" href="#静态生命周期">静态生命周期</a></h2>
<p>在 Rust 中有一个非常特殊的生命周期,那就是 <code>'static</code>,拥有该生命周期的引用可以和整个程序活得一样久。</p>
<p>在之前我们学过字符串字面量,提到过它是被硬编码进 Rust 的二进制文件中,因此这些字符串变量全部具有 <code>'static</code> 的生命周期:</p>
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</span><span class="boring">fn main() {
</span>let s: &amp;'static str = "我没啥优点,就是活得久,嘿嘿";
<span class="boring">}</span></code></pre>
9 months ago
<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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
9 months ago
</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!("Announcement! {}", ann);
if x.len() &gt; y.len() {
x
} else {
y
}
}
<span class="boring">}</span></code></pre>
9 months ago
<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://practice-zh.course.rs/lifetime/basic.html">Rust By Practice</a>,支持代码在线编辑和运行,并提供详细的<a href="https://github.com/sunface/rust-by-practice/blob/master/solutions/lifetime/basic.md">习题解答</a></p>
</blockquote>
<h2 id="总结"><a class="header" href="#总结">总结</a></h2>
<p>我不知道支撑我一口气写完的勇气是什么,也许是不做完不爽夫斯基,也许是一些读者对本书的期待,不管如何,这章足足写了 17000 字,可惜不是写小说,不然肯定可以获取很多月票 :)</p>
<p>从本章开始,最大的收获就是可以在结构体中使用引用类型了,说实话,为了引入这个特性,我已经憋了足足 N 个章节……</p>
<p>但是,还没完,是的,就算是将近两万字,生命周期的旅程依然没有完结,在本书的进阶部分,我们将介绍一些关于生命周期的高级特性,这些特性你在其它中文书中目前还看不到的。</p>
</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">
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg></span>
9 months ago
</a>
<a rel="next prefetch" href="../basic/result-error/intro.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg></span>
9 months ago
</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">
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg></span>
9 months ago
</a>
<a rel="next prefetch" href="../basic/result-error/intro.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg></span>
9 months ago
</a>
</nav>
</div>
<template id=fa-eye><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M288 32c-80.8 0-145.5 36.8-192.6 80.6C48.6 156 17.3 208 2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6C17.3 304 48.6 356 95.4 399.4C142.5 443.2 207.2 480 288 480s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C433.5 68.8 368.8 32 288 32zM432 256c0 79.5-64.5 144-144 144s-144-64.5-144-144s64.5-144 144-144s144 64.5 144 144zM288 192c0 35.3-28.7 64-64 64c-11.5 0-22.3-3-31.6-8.4c-.2 2.8-.4 5.5-.4 8.4c0 53 43 96 96 96s96-43 96-96s-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6z"/></svg></span></template>
<template id=fa-eye-slash><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2S-1.2 34.7 9.2 42.9l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7L525.6 386.7c39.6-40.6 66.4-86.1 79.9-118.4c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C465.5 68.8 400.8 32 320 32c-68.2 0-125 26.3-169.3 60.8L38.8 5.1zM223.1 149.5C248.6 126.2 282.7 112 320 112c79.5 0 144 64.5 144 144c0 24.9-6.3 48.3-17.4 68.7L408 294.5c5.2-11.8 8-24.8 8-38.5c0-53-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6c0 10.2-2.4 19.8-6.6 28.3l-90.3-70.8zm223.1 298L373 389.9c-16.4 6.5-34.3 10.1-53 10.1c-79.5 0-144-64.5-144-144c0-6.9 .5-13.6 1.4-20.2L83.1 161.5C60.3 191.2 44 220.8 34.5 243.7c-3.3 7.9-3.3 16.7 0 24.6c14.9 35.7 46.2 87.7 93 131.1C174.5 443.2 239.2 480 320 480c47.8 0 89.9-12.9 126.2-32.5z"/></svg></span></template>
<template id=fa-copy><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"/></svg></span></template>
<template id=fa-play><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M73 39c-14.8-9.1-33.4-9.4-48.5-.9S0 62.6 0 80V432c0 17.4 9.4 33.4 24.5 41.9s33.7 8.1 48.5-.9L361 297c14.3-8.7 23-24.2 23-41s-8.7-32.2-23-41L73 39z"/></svg></span></template>
<template id=fa-clock-rotate-left><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M75 75L41 41C25.9 25.9 0 36.6 0 57.9V168c0 13.3 10.7 24 24 24H134.1c21.4 0 32.1-25.9 17-41l-30.8-30.8C155 85.5 203 64 256 64c106 0 192 86 192 192s-86 192-192 192c-40.8 0-78.6-12.7-109.7-34.4c-14.5-10.1-34.4-6.6-44.6 7.9s-6.6 34.4 7.9 44.6C151.2 495 201.7 512 256 512c141.4 0 256-114.6 256-256S397.4 0 256 0C185.3 0 121.3 28.7 75 75zm181 53c-13.3 0-24 10.7-24 24V256c0 6.4 2.5 12.5 7 17l72 72c9.4 9.4 24.6 9.4 33.9 0s9.4-24.6 0-33.9l-65-65V152c0-13.3-10.7-24-24-24z"/></svg></span></template>
9 months ago
<script>
window.playground_copyable = true;
</script>
<script src="../ace-2a3cd908.js"></script>
<script src="../mode-rust-2c9d5c9a.js"></script>
<script src="../editor-16ca416c.js"></script>
<script src="../theme-dawn-4493f9c8.js"></script>
<script src="../theme-tomorrow_night-9dbe62a9.js"></script>
9 months ago
<script src="../elasticlunr-ef4e11c1.min.js"></script>
<script src="../mark-09e88c2c.min.js"></script>
<script src="../searcher-c2a407aa.js"></script>
9 months ago
<script src="../clipboard-1626706a.min.js"></script>
<script src="../highlight-abc7f01d.js"></script>
<script src="../book-a0b12cfe.js"></script>
9 months ago
<!-- Custom JS scripts -->
<script src="../assets/custom-7d8ae1df.js"></script>
<script src="../assets/bigPicture-be03f9c8.js"></script>
9 months ago
</div>
</body>
</html>