|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="zh-CN" class="light" dir="ltr">
|
|
|
|
|
<head>
|
|
|
|
|
<!-- Book generated using mdBook -->
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>深入生命周期 - Rust语言圣经(Rust Course)</title>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom HTML head -->
|
|
|
|
|
|
|
|
|
|
<meta name="description" content="">
|
|
|
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
|
|
|
<meta name="theme-color" content="#ffffff">
|
|
|
|
|
|
|
|
|
|
<link rel="icon" href="../../favicon.svg">
|
|
|
|
|
<link rel="shortcut icon" href="../../favicon.png">
|
|
|
|
|
<link rel="stylesheet" href="../../css/variables.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/general.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/chrome.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/print.css" media="print">
|
|
|
|
|
|
|
|
|
|
<!-- Fonts -->
|
|
|
|
|
<link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
|
|
|
|
|
<link rel="stylesheet" href="../../fonts/fonts.css">
|
|
|
|
|
|
|
|
|
|
<!-- Highlight.js Stylesheets -->
|
|
|
|
|
<link rel="stylesheet" href="../../highlight.css">
|
|
|
|
|
<link rel="stylesheet" href="../../tomorrow-night.css">
|
|
|
|
|
<link rel="stylesheet" href="../../ayu-highlight.css">
|
|
|
|
|
|
|
|
|
|
<!-- Custom theme stylesheets -->
|
|
|
|
|
<link rel="stylesheet" href="../../theme/style.css">
|
|
|
|
|
|
|
|
|
|
</head>
|
|
|
|
|
<body class="sidebar-visible no-js">
|
|
|
|
|
<div id="body-container">
|
|
|
|
|
<!-- Provide site root to javascript -->
|
|
|
|
|
<script>
|
|
|
|
|
var path_to_root = "../../";
|
|
|
|
|
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
|
|
|
|
<script>
|
|
|
|
|
try {
|
|
|
|
|
var theme = localStorage.getItem('mdbook-theme');
|
|
|
|
|
var sidebar = localStorage.getItem('mdbook-sidebar');
|
|
|
|
|
|
|
|
|
|
if (theme.startsWith('"') && theme.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
|
|
|
|
}
|
|
|
|
|
} catch (e) { }
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Set the theme before any content is loaded, prevents flash -->
|
|
|
|
|
<script>
|
|
|
|
|
var theme;
|
|
|
|
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|
|
|
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
|
|
|
|
var html = document.querySelector('html');
|
|
|
|
|
html.classList.remove('light')
|
|
|
|
|
html.classList.add(theme);
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
body.classList.remove('no-js')
|
|
|
|
|
body.classList.add('js');
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
|
|
|
|
|
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
|
|
|
<script>
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
var sidebar = null;
|
|
|
|
|
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
|
|
|
|
|
if (document.body.clientWidth >= 1080) {
|
|
|
|
|
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
|
|
|
|
sidebar = sidebar || 'visible';
|
|
|
|
|
} else {
|
|
|
|
|
sidebar = 'hidden';
|
|
|
|
|
}
|
|
|
|
|
sidebar_toggle.checked = sidebar === 'visible';
|
|
|
|
|
body.classList.remove('sidebar-visible');
|
|
|
|
|
body.classList.add("sidebar-" + sidebar);
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
|
|
|
|
<div class="sidebar-scrollbox">
|
|
|
|
|
<ol class="chapter"><li class="chapter-item affix "><a href="../../about-book.html">关于本书</a></li><li class="chapter-item affix "><a href="../../into-rust.html">进入 Rust 编程世界</a></li><li class="chapter-item affix "><a href="../../first-try/sth-you-should-not-do.html">避免从入门到放弃</a></li><li class="chapter-item affix "><a href="../../community.html">社区和锈书</a></li><li class="spacer"></li><li class="chapter-item affix "><a href="../../some-thoughts.html">Xobserve: 一切皆可观测</a></li><li class="chapter-item affix "><a href="../../beat-ai.html">BeatAI: 工程师 AI 入门圣经</a></li><li class="chapter-item affix "><li class="part-title">Rust 语言基础学习</li><li class="spacer"></li><li class="chapter-item "><a href="../../first-try/intro.html"><strong aria-hidden="true">1.</strong> 寻找牛刀,以便小试</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../first-try/installation.html"><strong aria-hidden="true">1.1.</strong> 安装 Rust 环境</a></li><li class="chapter-item "><a href="../../first-try/editor.html"><strong aria-hidden="true">1.2.</strong> 墙推 VSCode!</a></li><li class="chapter-item "><a href="../../first-try/cargo.html"><strong aria-hidden="true">1.3.</strong> 认识 Cargo</a></li><li class="chapter-item "><a href="../../first-try/hello-world.html"><strong aria-hidden="true">1.4.</strong> 不仅仅是 Hello world</a></li><li class="chapter-item "><a href="../../first-try/slowly-downloading.html"><strong aria-hidden="true">1.5.</strong> 下载依赖太慢了?</a></li></ol></li><li class="chapter-item "><a href="../../basic/intro.html"><strong aria-hidden="true">2.</strong> Rust 基础入门</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/variable.html"><strong aria-hidden="true">2.1.</strong> 变量绑定与解构</a></li><li class="chapter-item "><a href="../../basic/base-type/index.html"><strong aria-hidden="true">2.2.</strong> 基本类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/base-type/numbers.html"><strong aria-hidden="true">2.2.1.</strong> 数值类型</a></li><li class="chapter-item "><a href="../../basic/base-type/char-bool.html"><strong aria-hidden="true">2.2.2.</strong> 字符、布尔、单元类型</a></li><li class="chapter-item "><a href="../../basic/base-type/statement-expression.html"><strong aria-hidden="true">2.2.3.</strong> 语句与表达式</a></li><li class="chapter-item "><a href="../../basic/base-type/function.html"><strong aria-hidden="true">2.2.4.</strong> 函数</a></li></ol></li><li class="chapter-item "><a href="../../basic/ownership/index.html"><strong aria-hidden="true">2.3.</strong> 所有权和借用</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/ownership/ownership.html"><strong aria-hidden="true">2.3.1.</strong> 所有权</a></li><li class="chapter-item "><a href="../../basic/ownership/borrowing.html"><strong aria-hidden="true">2.3.2.</strong> 引用与借用</a></li></ol></li><li class="chapter-item "><a href="../../basic/compound-type/intro.html"><strong aria-hidden="true">2.4.</strong> 复合类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/compound-type/string-slice.html"><strong aria-hidden="true">2.4.1.</strong> 字符串与切片</a></li><li class="chapter-item "><a href="../../basic/compound-type/tuple.html"><strong aria-hidden="true">2.4.2.</strong> 元组</a></li><li class="chapter-item "><a href="../../basic/compound-type/struct.html"><strong aria-hidden="true">2.4.3.</strong> 结构体</a></li><li class="chapter-item "><a href="../../basic/compound-type/enum.html"><strong aria-hidden="true">2.4.4.</strong> 枚举</a></li><li class="chapter-item "><a href="../../basic/compound-type/array.html"><strong aria-hidden="true">2.4.5.</strong> 数组</a></l
|
|
|
|
|
</div>
|
|
|
|
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
|
|
|
|
<div class="sidebar-resize-indicator"></div>
|
|
|
|
|
</div>
|
|
|
|
|
</nav>
|
|
|
|
|
|
|
|
|
|
<!-- Track and set sidebar scroll position -->
|
|
|
|
|
<script>
|
|
|
|
|
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
|
|
|
|
|
sidebarScrollbox.addEventListener('click', function(e) {
|
|
|
|
|
if (e.target.tagName === 'A') {
|
|
|
|
|
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
|
|
|
|
|
}
|
|
|
|
|
}, { passive: true });
|
|
|
|
|
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
|
|
|
|
|
sessionStorage.removeItem('sidebar-scroll');
|
|
|
|
|
if (sidebarScrollTop) {
|
|
|
|
|
// preserve sidebar scroll position when navigating via links within sidebar
|
|
|
|
|
sidebarScrollbox.scrollTop = sidebarScrollTop;
|
|
|
|
|
} else {
|
|
|
|
|
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
|
|
|
|
|
var activeSection = document.querySelector('#sidebar .active');
|
|
|
|
|
if (activeSection) {
|
|
|
|
|
activeSection.scrollIntoView({ block: 'center' });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<div id="page-wrapper" class="page-wrapper">
|
|
|
|
|
|
|
|
|
|
<div class="page">
|
|
|
|
|
<div id="menu-bar-hover-placeholder"></div>
|
|
|
|
|
<div id="menu-bar" class="menu-bar sticky">
|
|
|
|
|
<div class="left-buttons">
|
|
|
|
|
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
|
|
|
|
<i class="fa fa-bars"></i>
|
|
|
|
|
</label>
|
|
|
|
|
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
|
|
|
|
<i class="fa fa-paint-brush"></i>
|
|
|
|
|
</button>
|
|
|
|
|
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
|
|
|
|
</ul>
|
|
|
|
|
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
|
|
|
|
<i class="fa fa-search"></i>
|
|
|
|
|
</button>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<h1 class="menu-title">Rust语言圣经(Rust Course)</h1>
|
|
|
|
|
|
|
|
|
|
<div class="right-buttons">
|
|
|
|
|
<a href="../../print.html" title="Print this book" aria-label="Print this book">
|
|
|
|
|
<i id="print-button" class="fa fa-print"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a href="https://github.com/sunface/rust-course" title="Git repository" aria-label="Git repository">
|
|
|
|
|
<i id="git-repository-button" class="fa fa-github"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a href="https://github.com/sunface/rust-course/edit/main/src/advance/lifetime/advance.md" title="Suggest an edit" aria-label="Suggest an edit">
|
|
|
|
|
<i id="git-edit-button" class="fa fa-edit"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div id="search-wrapper" class="hidden">
|
|
|
|
|
<form id="searchbar-outer" class="searchbar-outer">
|
|
|
|
|
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
|
|
|
|
|
</form>
|
|
|
|
|
<div id="searchresults-outer" class="searchresults-outer hidden">
|
|
|
|
|
<div id="searchresults-header" class="searchresults-header"></div>
|
|
|
|
|
<ul id="searchresults">
|
|
|
|
|
</ul>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
|
|
|
|
<script>
|
|
|
|
|
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
|
|
|
|
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
|
|
|
|
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
|
|
|
|
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
|
|
|
|
});
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<div id="content" class="content">
|
|
|
|
|
<!-- Page table of contents -->
|
|
|
|
|
<div class="sidetoc"><nav class="pagetoc"></nav></div>
|
|
|
|
|
<main>
|
|
|
|
|
<h1 id="深入生命周期"><a class="header" href="#深入生命周期">深入生命周期</a></h1>
|
|
|
|
|
<p>其实关于生命周期的常用特性,在上一节中,我们已经概括得差不多了,本章主要讲解生命周期的一些高级或者不为人知的特性。对于新手,完全可以跳过本节内容,进行下一章节的学习。</p>
|
|
|
|
|
<h2 id="不太聪明的生命周期检查"><a class="header" href="#不太聪明的生命周期检查">不太聪明的生命周期检查</a></h2>
|
|
|
|
|
<p>在 Rust 语言学习中,一个很重要的部分就是阅读一些你可能不经常遇到,但是一旦遇到就难以理解的代码,这些代码往往最令人头疼的就是生命周期,这里我们就来看看一些本以为可以编译,但是却因为生命周期系统不够聪明导致编译失败的代码。</p>
|
|
|
|
|
<h4 id="例子-1"><a class="header" href="#例子-1">例子 1</a></h4>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">#[derive(Debug)]
|
|
|
|
|
struct Foo;
|
|
|
|
|
|
|
|
|
|
impl Foo {
|
|
|
|
|
fn mutate_and_share(&mut self) -> &Self {
|
|
|
|
|
&*self
|
|
|
|
|
}
|
|
|
|
|
fn share(&self) {}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let mut foo = Foo;
|
|
|
|
|
let loan = foo.mutate_and_share();
|
|
|
|
|
foo.share();
|
|
|
|
|
println!("{:?}", loan);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>上面的代码中,<code>foo.mutate_and_share()</code> 虽然借用了 <code>&mut self</code>,但是它最终返回的是一个 <code>&self</code>,然后赋值给 <code>loan</code>,因此理论上来说它最终是进行了不可变借用,同时 <code>foo.share</code> 也进行了不可变借用,那么根据 Rust 的借用规则:多个不可变借用可以同时存在,因此该代码应该编译通过。</p>
|
|
|
|
|
<p>事实上,运行代码后,你将看到一个错误:</p>
|
|
|
|
|
<pre><code class="language-console">error[E0502]: cannot borrow `foo` as immutable because it is also borrowed as mutable
|
|
|
|
|
--> src/main.rs:12:5
|
|
|
|
|
|
|
|
|
|
|
11 | let loan = foo.mutate_and_share();
|
|
|
|
|
| ---------------------- mutable borrow occurs here
|
|
|
|
|
12 | foo.share();
|
|
|
|
|
| ^^^^^^^^^^^ immutable borrow occurs here
|
|
|
|
|
13 | println!("{:?}", loan);
|
|
|
|
|
| ---- mutable borrow later used here
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>编译器的提示在这里其实有些难以理解,因为可变借用仅在 <code>mutate_and_share</code> 方法内部有效,出了该方法后,就只有返回的不可变借用,因此,按理来说可变借用不应该在 <code>main</code> 的作用范围内存在。</p>
|
|
|
|
|
<p>对于这个反直觉的事情,让我们用生命周期来解释下,可能你就很好理解了:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">struct Foo;
|
|
|
|
|
|
|
|
|
|
impl Foo {
|
|
|
|
|
fn mutate_and_share<'a>(&'a mut self) -> &'a Self {
|
|
|
|
|
&'a *self
|
|
|
|
|
}
|
|
|
|
|
fn share<'a>(&'a self) {}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
'b: {
|
|
|
|
|
let mut foo: Foo = Foo;
|
|
|
|
|
'c: {
|
|
|
|
|
let loan: &'c Foo = Foo::mutate_and_share::<'c>(&'c mut foo);
|
|
|
|
|
'd: {
|
|
|
|
|
Foo::share::<'d>(&'d foo);
|
|
|
|
|
}
|
|
|
|
|
println!("{:?}", loan);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>以上是模拟了编译器的生命周期标注后的代码,可以注意到 <code>&mut foo</code> 和 <code>loan</code> 的生命周期都是 <code>'c</code>。</p>
|
|
|
|
|
<p>还记得生命周期消除规则中的第三条吗?因为该规则,导致了 <code>mutate_and_share</code> 方法中,参数 <code>&mut self</code> 和返回值 <code>&self</code> 的生命周期是相同的,因此,若返回值的生命周期在 <code>main</code> 函数有效,那 <code>&mut self</code> 的借用也是在 <code>main</code> 函数有效。</p>
|
|
|
|
|
<p>这就解释了可变借用为啥会在 <code>main</code> 函数作用域内有效,最终导致 <code>foo.share()</code> 无法再进行不可变借用。</p>
|
|
|
|
|
<p>总结下:<code>&mut self</code> 借用的生命周期和 <code>loan</code> 的生命周期相同,将持续到 <code>println</code> 结束。而在此期间 <code>foo.share()</code> 又进行了一次不可变 <code>&foo</code> 借用,违背了可变借用与不可变借用不能同时存在的规则,最终导致了编译错误。</p>
|
|
|
|
|
<p>上述代码实际上完全是正确的,但是因为生命周期系统的“粗糙实现”,导致了编译错误,目前来说,遇到这种生命周期系统不够聪明导致的编译错误,我们也没有太好的办法,只能修改代码去满足它的需求,并期待以后它会更聪明。</p>
|
|
|
|
|
<h4 id="例子-2"><a class="header" href="#例子-2">例子 2</a></h4>
|
|
|
|
|
<p>再来看一个例子:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">#![allow(unused)]
|
|
|
|
|
fn main() {
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
use std::hash::Hash;
|
|
|
|
|
fn get_default<'m, K, V>(map: &'m mut HashMap<K, V>, key: K) -> &'m mut V
|
|
|
|
|
where
|
|
|
|
|
K: Clone + Eq + Hash,
|
|
|
|
|
V: Default,
|
|
|
|
|
{
|
|
|
|
|
match map.get_mut(&key) {
|
|
|
|
|
Some(value) => value,
|
|
|
|
|
None => {
|
|
|
|
|
map.insert(key.clone(), V::default());
|
|
|
|
|
map.get_mut(&key).unwrap()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
</code></pre></pre>
|
|
|
|
|
<p>这段代码不能通过编译的原因是编译器未能精确地判断出某个可变借用不再需要,反而谨慎的给该借用安排了一个很大的作用域,结果导致后续的借用失败:</p>
|
|
|
|
|
<pre><code class="language-console">error[E0499]: cannot borrow `*map` as mutable more than once at a time
|
|
|
|
|
--> src/main.rs:13:17
|
|
|
|
|
|
|
|
|
|
|
5 | fn get_default<'m, K, V>(map: &'m mut HashMap<K, V>, key: K) -> &'m mut V
|
|
|
|
|
| -- lifetime `'m` defined here
|
|
|
|
|
...
|
|
|
|
|
10 | match map.get_mut(&key) {
|
|
|
|
|
| - ----------------- first mutable borrow occurs here
|
|
|
|
|
| _________|
|
|
|
|
|
| |
|
|
|
|
|
11 | | Some(value) => value,
|
|
|
|
|
12 | | None => {
|
|
|
|
|
13 | | map.insert(key.clone(), V::default());
|
|
|
|
|
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
|
|
|
|
|
14 | | map.get_mut(&key).unwrap()
|
|
|
|
|
15 | | }
|
|
|
|
|
16 | | }
|
|
|
|
|
| |_________- returning this value requires that `*map` is borrowed for `'m`
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>分析代码可知在 <code>match map.get_mut(&key)</code> 方法调用完成后,对 <code>map</code> 的可变借用就可以结束了。但从报错看来,编译器不太聪明,它认为该借用会持续到整个 <code>match</code> 语句块的结束(第 16 行处),这便造成了后续借用的失败。</p>
|
|
|
|
|
<p>类似的例子还有很多,由于篇幅有限,就不在这里一一列举,如果大家想要阅读更多的类似代码,可以看看<a href="https://github.com/sunface/rust-codes">《Rust 代码鉴赏》</a>一书。</p>
|
|
|
|
|
<h2 id="无界生命周期"><a class="header" href="#无界生命周期">无界生命周期</a></h2>
|
|
|
|
|
<p>不安全代码(<code>unsafe</code>)经常会凭空产生引用或生命周期,这些生命周期被称为是 <strong>无界(unbound)</strong> 的。</p>
|
|
|
|
|
<p>无界生命周期往往是在解引用一个裸指针(裸指针 raw pointer)时产生的,换句话说,它是凭空产生的,因为输入参数根本就没有这个生命周期:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>fn f<'a, T>(x: *const T) -> &'a T {
|
|
|
|
|
unsafe {
|
|
|
|
|
&*x
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>上述代码中,参数 <code>x</code> 是一个裸指针,它并没有任何生命周期,然后通过 <code>unsafe</code> 操作后,它被进行了解引用,变成了一个 Rust 的标准引用类型,该类型必须要有生命周期,也就是 <code>'a</code>。</p>
|
|
|
|
|
<p>可以看出 <code>'a</code> 是凭空产生的,因此它是无界生命周期。这种生命周期由于没有受到任何约束,因此它想要多大就多大,这实际上比 <code>'static</code> 要强大。例如 <code>&'static &'a T</code> 是无效类型,但是无界生命周期 <code>&'unbounded &'a T</code> 会被视为 <code>&'a &'a T</code> 从而通过编译检查,因为它可大可小,就像孙猴子的金箍棒一般。</p>
|
|
|
|
|
<p>我们在实际应用中,要尽量避免这种无界生命周期。最简单的避免无界生命周期的方式就是在函数声明中运用生命周期消除规则。<strong>若一个输出生命周期被消除了,那么必定因为有一个输入生命周期与之对应</strong>。</p>
|
|
|
|
|
<h2 id="生命周期约束-hrtb"><a class="header" href="#生命周期约束-hrtb">生命周期约束 HRTB</a></h2>
|
|
|
|
|
<p>生命周期约束跟特征约束类似,都是通过形如 <code>'a: 'b</code> 的语法,来说明两个生命周期的长短关系。</p>
|
|
|
|
|
<h4 id="a-b"><a class="header" href="#a-b">'a: 'b</a></h4>
|
|
|
|
|
<p>假设有两个引用 <code>&'a i32</code> 和 <code>&'b i32</code>,它们的生命周期分别是 <code>'a</code> 和 <code>'b</code>,若 <code>'a</code> >= <code>'b</code>,则可以定义 <code>'a:'b</code>,表示 <code>'a</code> 至少要活得跟 <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>struct DoubleRef<'a,'b:'a, T> {
|
|
|
|
|
r: &'a T,
|
|
|
|
|
s: &'b T
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>例如上述代码定义一个结构体,它拥有两个引用字段,类型都是泛型 <code>T</code>,每个引用都拥有自己的生命周期,由于我们使用了生命周期约束 <code>'b: 'a</code>,因此 <code>'b</code> 必须活得比 <code>'a</code> 久,也就是结构体中的 <code>s</code> 字段引用的值必须要比 <code>r</code> 字段引用的值活得要久。</p>
|
|
|
|
|
<h4 id="t-a"><a class="header" href="#t-a">T: 'a</a></h4>
|
|
|
|
|
<p>表示类型 <code>T</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>struct Ref<'a, T: 'a> {
|
|
|
|
|
r: &'a T
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>因为结构体字段 <code>r</code> 引用了 <code>T</code>,因此 <code>r</code> 的生命周期 <code>'a</code> 必须要比 <code>T</code> 的生命周期更短(被引用者的生命周期必须要比引用长)。</p>
|
|
|
|
|
<p>在 Rust 1.30 版本之前,该写法是必须的,但是从 1.31 版本开始,编译器可以自动推导 <code>T: 'a</code> 类型的约束,因此我们只需这样写即可:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>struct Ref<'a, T> {
|
|
|
|
|
r: &'a T
|
|
|
|
|
}
|
|
|
|
|
<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<'a> {
|
|
|
|
|
part: &'a str,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<'a: 'b, 'b> ImportantExcerpt<'a> {
|
|
|
|
|
fn announce_and_return_part(&'a self, announcement: &'b str) -> &'b str {
|
|
|
|
|
println!("Attention please: {}", announcement);
|
|
|
|
|
self.part
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>上面的例子中必须添加约束 <code>'a: 'b</code> 后,才能成功编译,因为 <code>self.part</code> 的生命周期与 <code>self</code>的生命周期一致,将 <code>&'a</code> 类型的生命周期强行转换为 <code>&'b</code> 类型,会报错,只有在 <code>'a</code> >= <code>'b</code> 的情况下,<code>'a</code> 才能转换成 <code>'b</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>fn fn_elision(x: &i32) -> &i32 { x }
|
|
|
|
|
let closure_slision = |x: &i32| -> &i32 { x };
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>乍一看,这段代码比古天乐还平平无奇,能有什么问题呢?来,拄拐走两圈试试:</p>
|
|
|
|
|
<pre><code class="language-console">error: lifetime may not live long enough
|
|
|
|
|
--> src/main.rs:39:39
|
|
|
|
|
|
|
|
|
|
|
39 | let closure = |x: &i32| -> &i32 { x }; // fails
|
|
|
|
|
| - - ^ returning this value requires that `'1` must outlive `'2`
|
|
|
|
|
| | |
|
|
|
|
|
| | let's call the lifetime of this reference `'2`
|
|
|
|
|
| let's call the lifetime of this reference `'1`
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>咦?竟然报错了,明明两个一模一样功能的函数,一个正常编译,一个却报错,错误原因是编译器无法推测返回的引用和传入的引用谁活得更久!</p>
|
|
|
|
|
<p>真的是非常奇怪的错误,学过上一节的读者应该都记得这样一条生命周期消除规则:<strong>如果函数参数中只有一个引用类型,那该引用的生命周期会被自动分配给所有的返回引用</strong>。我们当前的情况完美符合, <code>function</code> 函数的顺利编译通过,就充分说明了问题。</p>
|
|
|
|
|
<p>先给出一个结论:<strong>这个问题,可能很难被解决,建议大家遇到后,还是老老实实用正常的函数,不要秀闭包了</strong>。</p>
|
|
|
|
|
<p>对于函数的生命周期而言,它的消除规则之所以能生效是因为它的生命周期完全体现在签名的引用类型上,在函数体中无需任何体现:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>fn fn_elision(x: &i32) -> &i32 {..}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>因此编译器可以做各种编译优化,也很容易根据参数和返回值进行生命周期的分析,最终得出消除规则。</p>
|
|
|
|
|
<p>可是闭包,并没有函数那么简单,它的生命周期分散在参数和闭包函数体中(主要是它没有确切的返回值签名):</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>let closure_slision = |x: &i32| -> &i32 { x };
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>编译器就必须深入到闭包函数体中,去分析和推测生命周期,复杂度因此急剧提升:试想一下,编译器该如何从复杂的上下文中分析出参数引用的生命周期和闭包体中生命周期的关系?</p>
|
|
|
|
|
<p>由于上述原因(当然,实际情况复杂的多),Rust 语言开发者目前其实是有意针对函数和闭包实现了两种不同的生命周期消除规则。</p>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p><strong>用 <code>Fn</code> 特征解决闭包生命周期</strong></p>
|
|
|
|
|
<p>之前我们提到了很难解决,但是并没有完全堵死(论文字的艺术- , -) 这不 @Ykong1337 同学就带了一个解决方法,为他点赞!</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let closure_slision = fun(|x: &i32| -> &i32 { x });
|
|
|
|
|
assert_eq!(*closure_slision(&45), 45);
|
|
|
|
|
// Passed !
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn fun<T, F: Fn(&T) -> &T>(f: F) -> F {
|
|
|
|
|
f
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<h2 id="nll-non-lexical-lifetime"><a class="header" href="#nll-non-lexical-lifetime">NLL (Non-Lexical Lifetime)</a></h2>
|
|
|
|
|
<p>之前我们在<a href="https://course.rs/basic/ownership/borrowing.html#NLL">引用与借用</a>那一章其实有讲到过这个概念,简单来说就是:<strong>引用的生命周期正常来说应该从借用开始一直持续到作用域结束</strong>,但是这种规则会让多引用共存的情况变得更复杂:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let mut s = String::from("hello");
|
|
|
|
|
|
|
|
|
|
let r1 = &s;
|
|
|
|
|
let r2 = &s;
|
|
|
|
|
println!("{} and {}", r1, r2);
|
|
|
|
|
// 新编译器中,r1,r2作用域在这里结束
|
|
|
|
|
|
|
|
|
|
let r3 = &mut s;
|
|
|
|
|
println!("{}", r3);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>按照上述规则,这段代码将会报错,因为 <code>r1</code> 和 <code>r2</code> 的不可变引用将持续到 <code>main</code> 函数结束,而在此范围内,我们又借用了 <code>r3</code> 的可变引用,这违反了借用的规则:要么多个不可变借用,要么一个可变借用。</p>
|
|
|
|
|
<p>好在,该规则从 1.31 版本引入 <code>NLL</code> 后,就变成了:<strong>引用的生命周期从借用处开始,一直持续到最后一次使用的地方</strong>。</p>
|
|
|
|
|
<p>按照最新的规则,我们再来分析一下上面的代码。<code>r1</code> 和 <code>r2</code> 不可变借用在 <code>println!</code> 后就不再使用,因此生命周期也随之结束,那么 <code>r3</code> 的借用就不再违反借用的规则,皆大欢喜。</p>
|
|
|
|
|
<p>再来看一段关于 <code>NLL</code> 的代码解释:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>let mut u = 0i32;
|
|
|
|
|
let mut v = 1i32;
|
|
|
|
|
let mut w = 2i32;
|
|
|
|
|
|
|
|
|
|
// lifetime of `a` = α ∪ β ∪ γ
|
|
|
|
|
let mut a = &mut u; // --+ α. lifetime of `&mut u` --+ lexical "lifetime" of `&mut u`,`&mut u`, `&mut w` and `a`
|
|
|
|
|
use(a); // | |
|
|
|
|
|
*a = 3; // <-----------------+ |
|
|
|
|
|
... // |
|
|
|
|
|
a = &mut v; // --+ β. lifetime of `&mut v` |
|
|
|
|
|
use(a); // | |
|
|
|
|
|
*a = 4; // <-----------------+ |
|
|
|
|
|
... // |
|
|
|
|
|
a = &mut w; // --+ γ. lifetime of `&mut w` |
|
|
|
|
|
use(a); // | |
|
|
|
|
|
*a = 5; // <-----------------+ <--------------------------+
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>这段代码一目了然,<code>a</code> 有三段生命周期:<code>α</code>,<code>β</code>,<code>γ</code>,每一段生命周期都随着当前值的最后一次使用而结束。</p>
|
|
|
|
|
<p>在实际项目中,<code>NLL</code> 规则可以大幅减少引用冲突的情况,极大的便利了用户,因此广受欢迎,最终该规则甚至演化成一个独立的项目,未来可能会进一步简化我们的使用,<code>Polonius</code>:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li><a href="https://github.com/rust-lang/polonius">项目地址</a></li>
|
|
|
|
|
<li><a href="http://smallcultfollowing.com/babysteps/blog/2018/04/27/an-alias-based-formulation-of-the-borrow-checker/">具体介绍</a></li>
|
|
|
|
|
</ul>
|
|
|
|
|
<h1 id="reborrow-再借用"><a class="header" href="#reborrow-再借用">Reborrow 再借用</a></h1>
|
|
|
|
|
<p>学完 <code>NLL</code> 后,我们就有了一定的基础,可以继续学习关于借用和生命周期的一个高级内容:<strong>再借用</strong>。</p>
|
|
|
|
|
<p>先来看一段代码:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">#[derive(Debug)]
|
|
|
|
|
struct Point {
|
|
|
|
|
x: i32,
|
|
|
|
|
y: i32,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Point {
|
|
|
|
|
fn move_to(&mut self, x: i32, y: i32) {
|
|
|
|
|
self.x = x;
|
|
|
|
|
self.y = y;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let mut p = Point { x: 0, y: 0 };
|
|
|
|
|
let r = &mut p;
|
|
|
|
|
let rr: &Point = &*r;
|
|
|
|
|
|
|
|
|
|
println!("{:?}", rr);
|
|
|
|
|
r.move_to(10, 10);
|
|
|
|
|
println!("{:?}", r);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>以上代码,大家可能会觉得可变引用 <code>r</code> 和不可变引用 <code>rr</code> 同时存在会报错吧?但是事实上并不会,原因在于 <code>rr</code> 是对 <code>r</code> 的再借用。</p>
|
|
|
|
|
<p>对于再借用而言,<code>rr</code> 再借用时不会破坏借用规则,但是你不能在它的生命周期内再使用原来的借用 <code>r</code>,来看看对上段代码的分析:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let mut p = Point { x: 0, y: 0 };
|
|
|
|
|
let r = &mut p;
|
|
|
|
|
// reborrow! 此时对`r`的再借用不会导致跟上面的借用冲突
|
|
|
|
|
let rr: &Point = &*r;
|
|
|
|
|
|
|
|
|
|
// 再借用`rr`最后一次使用发生在这里,在它的生命周期中,我们并没有使用原来的借用`r`,因此不会报错
|
|
|
|
|
println!("{:?}", rr);
|
|
|
|
|
|
|
|
|
|
// 再借用结束后,才去使用原来的借用`r`
|
|
|
|
|
r.move_to(10, 10);
|
|
|
|
|
println!("{:?}", r);
|
|
|
|
|
}</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>use std::vec::Vec;
|
|
|
|
|
fn read_length(strings: &mut Vec<String>) -> usize {
|
|
|
|
|
strings.len()
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>如上所示,函数体内对参数的二次借用也是典型的 <code>Reborrow</code> 场景。</p>
|
|
|
|
|
<p>那么下面让我们来做件坏事,破坏这条规则,使其报错:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let mut p = Point { x: 0, y: 0 };
|
|
|
|
|
let r = &mut p;
|
|
|
|
|
let rr: &Point = &*r;
|
|
|
|
|
|
|
|
|
|
r.move_to(10, 10);
|
|
|
|
|
|
|
|
|
|
println!("{:?}", rr);
|
|
|
|
|
|
|
|
|
|
println!("{:?}", r);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>果然,破坏永远比重建简单 :) 只需要在 <code>rr</code> 再借用的生命周期内使用一次原来的借用 <code>r</code> 即可!</p>
|
|
|
|
|
<h2 id="生命周期消除规则补充"><a class="header" href="#生命周期消除规则补充">生命周期消除规则补充</a></h2>
|
|
|
|
|
<p>在上一节中,我们介绍了三大基础生命周期消除规则,实际上,随着 Rust 的版本进化,该规则也在不断演进,这里再介绍几个常见的消除规则:</p>
|
|
|
|
|
<h4 id="impl-块消除"><a class="header" href="#impl-块消除">impl 块消除</a></h4>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>impl<'a> Reader for BufReader<'a> {
|
|
|
|
|
// methods go here
|
|
|
|
|
// impl内部实际上没有用到'a
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>如果你以前写的<code>impl</code>块长上面这样,同时在 <code>impl</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 Reader for BufReader<'_> {
|
|
|
|
|
// methods go here
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p><code>'_</code> 称为匿名生命周期(anonymous lifetime),在这里表示 <code>BufReader</code> 有一个不使用的生命周期,我们可以忽略它,无需为它创建一个名称。</p>
|
|
|
|
|
<p>歪个楼,有读者估计会发问:既然用不到 <code>'a</code>,为何还要写出来?如果你仔细回忆下上一节的内容,里面有一句专门用粗体标注的文字:<strong>生命周期参数也是类型的一部分</strong>,因此 <code>BufReader<'a></code> 是一个完整的类型,在实现它的时候,你不能把 <code>'a</code> 给丢了!</p>
|
|
|
|
|
<h4 id="生命周期约束消除"><a class="header" href="#生命周期约束消除">生命周期约束消除</a></h4>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>// Rust 2015
|
|
|
|
|
struct Ref<'a, T: 'a> {
|
|
|
|
|
field: &'a T
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Rust 2018
|
|
|
|
|
struct Ref<'a, T> {
|
|
|
|
|
field: &'a T
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>在本节的生命周期约束中,也提到过,新版本 Rust 中,上面情况中的 <code>T: 'a</code> 可以被消除掉,当然,你也可以显式的声明,但是会影响代码可读性。关于类似的场景,Rust 团队计划在未来提供更多的消除规则,但是,你懂的,计划未来就等于未知。</p>
|
|
|
|
|
<h2 id="一个复杂的例子"><a class="header" href="#一个复杂的例子">一个复杂的例子</a></h2>
|
|
|
|
|
<p>下面是一个关于生命周期声明过大的例子,会较为复杂,希望大家能细细阅读,它能帮你对生命周期的理解更加深入。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">struct Interface<'a> {
|
|
|
|
|
manager: &'a mut Manager<'a>
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<'a> Interface<'a> {
|
|
|
|
|
pub fn noop(self) {
|
|
|
|
|
println!("interface consumed");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct Manager<'a> {
|
|
|
|
|
text: &'a str
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct List<'a> {
|
|
|
|
|
manager: Manager<'a>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<'a> List<'a> {
|
|
|
|
|
pub fn get_interface(&'a mut self) -> Interface {
|
|
|
|
|
Interface {
|
|
|
|
|
manager: &mut self.manager
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let mut list = List {
|
|
|
|
|
manager: Manager {
|
|
|
|
|
text: "hello"
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
list.get_interface().noop();
|
|
|
|
|
|
|
|
|
|
println!("Interface should be dropped here and the borrow released");
|
|
|
|
|
|
|
|
|
|
// 下面的调用会失败,因为同时有不可变/可变借用
|
|
|
|
|
// 但是Interface在之前调用完成后就应该被释放了
|
|
|
|
|
use_list(&list);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn use_list(list: &List) {
|
|
|
|
|
println!("{}", list.manager.text);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>运行后报错:</p>
|
|
|
|
|
<pre><code class="language-console">error[E0502]: cannot borrow `list` as immutable because it is also borrowed as mutable // `list`无法被借用,因为已经被可变借用
|
|
|
|
|
--> src/main.rs:40:14
|
|
|
|
|
|
|
|
|
|
|
34 | list.get_interface().noop();
|
|
|
|
|
| ---- mutable borrow occurs here // 可变借用发生在这里
|
|
|
|
|
...
|
|
|
|
|
40 | use_list(&list);
|
|
|
|
|
| ^^^^^
|
|
|
|
|
| |
|
|
|
|
|
| immutable borrow occurs here // 新的不可变借用发生在这
|
|
|
|
|
| mutable borrow later used here // 可变借用在这里结束
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>这段代码看上去并不复杂,实际上难度挺高的,首先在直觉上,<code>list.get_interface()</code> 借用的可变引用,按理来说应该在这行代码结束后,就归还了,但是为什么还能持续到 <code>use_list(&list)</code> 后面呢?</p>
|
|
|
|
|
<p>这是因为我们在 <code>get_interface</code> 方法中声明的 <code>lifetime</code> 有问题,该方法的参数的生命周期是 <code>'a</code>,而 <code>List</code> 的生命周期也是 <code>'a</code>,说明该方法至少活得跟 <code>List</code> 一样久,再回到 <code>main</code> 函数中,<code>list</code> 可以活到 <code>main</code> 函数的结束,因此 <code>list.get_interface()</code> 借用的可变引用也会活到 <code>main</code> 函数的结束,在此期间,自然无法再进行借用了。</p>
|
|
|
|
|
<p>要解决这个问题,我们需要为 <code>get_interface</code> 方法的参数给予一个不同于 <code>List<'a></code> 的生命周期 <code>'b</code>,最终代码如下:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">struct Interface<'b, 'a: 'b> {
|
|
|
|
|
manager: &'b mut Manager<'a>
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<'b, 'a: 'b> Interface<'b, 'a> {
|
|
|
|
|
pub fn noop(self) {
|
|
|
|
|
println!("interface consumed");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct Manager<'a> {
|
|
|
|
|
text: &'a str
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct List<'a> {
|
|
|
|
|
manager: Manager<'a>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<'a> List<'a> {
|
|
|
|
|
pub fn get_interface<'b>(&'b mut self) -> Interface<'b, 'a>
|
|
|
|
|
where 'a: 'b {
|
|
|
|
|
Interface {
|
|
|
|
|
manager: &mut self.manager
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
|
|
|
|
|
let mut list = List {
|
|
|
|
|
manager: Manager {
|
|
|
|
|
text: "hello"
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
list.get_interface().noop();
|
|
|
|
|
|
|
|
|
|
println!("Interface should be dropped here and the borrow released");
|
|
|
|
|
|
|
|
|
|
// 下面的调用可以通过,因为Interface的生命周期不需要跟list一样长
|
|
|
|
|
use_list(&list);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn use_list(list: &List) {
|
|
|
|
|
println!("{}", list.manager.text);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>至此,生命周期终于完结,两章超级长的内容,可以满足几乎所有对生命周期的学习目标。学完生命周期,意味着你正式入门了 Rust,只要再掌握几个常用概念,就可以上手写项目了。</p>
|
|
|
|
|
|
|
|
|
|
<div id="giscus-container"></div>
|
|
|
|
|
</main>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
|
<a rel="prev" href="../../advance/lifetime/intro.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="../../advance/lifetime/static.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="../../advance/lifetime/intro.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="../../advance/lifetime/static.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 = "advance/lifetime/advance.md"
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
|
|
<script src="../../assets/custom.js"></script>
|
|
|
|
|
<script src="../../assets/bigPicture.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|