|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="zh-CN" class="light" dir="ltr">
|
|
|
|
|
<head>
|
|
|
|
|
<!-- Book generated using mdBook -->
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>&'static 和 T: 'static - 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/static.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="static-和-t-static"><a class="header" href="#static-和-t-static">&'static 和 T: 'static</a></h1>
|
|
|
|
|
<p>Rust 的难点之一就在于它有不少容易混淆的概念,例如 <code>&str</code> 、<code>str</code> 与 <code>String</code>, 再比如本文标题那两位。不过与字符串也有不同,这两位对于普通用户来说往往是无需进行区分的,但是当大家想要深入学习或使用 Rust 时,它们就会成为成功路上的拦路虎了。</p>
|
|
|
|
|
<p>与生命周期的其它章节不同,本文短小精悍,阅读过程可谓相当轻松愉快,话不多说,let's go。</p>
|
|
|
|
|
<p><code>'static</code> 在 Rust 中是相当常见的,例如字符串字面值就具有 <code>'static</code> 生命周期:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let mark_twain: &str = "Samuel Clemens";
|
|
|
|
|
print_author(mark_twain);
|
|
|
|
|
}
|
|
|
|
|
fn print_author(author: &'static str) {
|
|
|
|
|
println!("{}", author);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>除此之外,特征对象的生命周期也是 <code>'static</code>,例如<a href="https://course.rs/compiler/fight-with-compiler/lifetime/closure-with-static.html#%E7%89%B9%E5%BE%81%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F">这里</a>所提到的。</p>
|
|
|
|
|
<p>除了 <code>&'static</code> 的用法外,我们在另外一种场景中也可以见到 <code>'static</code> 的使用:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::fmt::Display;
|
|
|
|
|
fn main() {
|
|
|
|
|
let mark_twain = "Samuel Clemens";
|
|
|
|
|
print(&mark_twain);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn print<T: Display + 'static>(message: &T) {
|
|
|
|
|
println!("{}", message);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>在这里,很明显 <code>'static</code> 是作为生命周期约束来使用了。 <strong>那么问题来了, <code>&'static</code> 和 <code>T: 'static</code> 的用法到底有何区别?</strong></p>
|
|
|
|
|
<h2 id="static"><a class="header" href="#static"><code>&'static</code></a></h2>
|
|
|
|
|
<p><code>&'static</code> 对于生命周期有着非常强的要求:一个引用必须要活得跟剩下的程序一样久,才能被标注为 <code>&'static</code>。</p>
|
|
|
|
|
<p>对于字符串字面量来说,它直接被打包到二进制文件中,永远不会被 <code>drop</code>,因此它能跟程序活得一样久,自然它的生命周期是 <code>'static</code>。</p>
|
|
|
|
|
<p>但是,<strong><code>&'static</code> 生命周期针对的仅仅是引用,而不是持有该引用的变量,对于变量来说,还是要遵循相应的作用域规则</strong> :</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::{slice::from_raw_parts, str::from_utf8_unchecked};
|
|
|
|
|
|
|
|
|
|
fn get_memory_location() -> (usize, usize) {
|
|
|
|
|
// “Hello World” 是字符串字面量,因此它的生命周期是 `'static`.
|
|
|
|
|
// 但持有它的变量 `string` 的生命周期就不一样了,它完全取决于变量作用域,对于该例子来说,也就是当前的函数范围
|
|
|
|
|
let string = "Hello World!";
|
|
|
|
|
let pointer = string.as_ptr() as usize;
|
|
|
|
|
let length = string.len();
|
|
|
|
|
(pointer, length)
|
|
|
|
|
// `string` 在这里被 drop 释放
|
|
|
|
|
// 虽然变量被释放,无法再被访问,但是数据依然还会继续存活
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn get_str_at_location(pointer: usize, length: usize) -> &'static str {
|
|
|
|
|
// 使用裸指针需要 `unsafe{}` 语句块
|
|
|
|
|
unsafe { from_utf8_unchecked(from_raw_parts(pointer as *const u8, length)) }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let (pointer, length) = get_memory_location();
|
|
|
|
|
let message = get_str_at_location(pointer, length);
|
|
|
|
|
println!(
|
|
|
|
|
"The {} bytes at 0x{:X} stored: {}",
|
|
|
|
|
length, pointer, message
|
|
|
|
|
);
|
|
|
|
|
// 如果大家想知道为何处理裸指针需要 `unsafe`,可以试着反注释以下代码
|
|
|
|
|
// let message = get_str_at_location(1000, 10);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>上面代码有两点值得注意:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li><code>&'static</code> 的引用确实可以和程序活得一样久,因为我们通过 <code>get_str_at_location</code> 函数直接取到了对应的字符串</li>
|
|
|
|
|
<li>持有 <code>&'static</code> 引用的变量,它的生命周期受到作用域的限制,大家务必不要搞混了</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<h2 id="t-static"><a class="header" href="#t-static"><code>T: 'static</code></a></h2>
|
|
|
|
|
<p>相比起来,这种形式的约束就有些复杂了。</p>
|
|
|
|
|
<p>首先,在以下两种情况下,<code>T: 'static</code> 与 <code>&'static</code> 有相同的约束:<code>T</code> 必须活得和程序一样久。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::fmt::Debug;
|
|
|
|
|
|
|
|
|
|
fn print_it<T: Debug + 'static>( input: T) {
|
|
|
|
|
println!( "'static value passed in is: {:?}", input );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn print_it1( input: impl Debug + 'static ) {
|
|
|
|
|
println!( "'static value passed in is: {:?}", input );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let i = 5;
|
|
|
|
|
|
|
|
|
|
print_it(&i);
|
|
|
|
|
print_it1(&i);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>以上代码会报错,原因很简单: <code>&i</code> 的生命周期无法满足 <code>'static</code> 的约束,如果大家将 <code>i</code> 修改为常量,那自然一切 OK。</p>
|
|
|
|
|
<p>见证奇迹的时候,请不要眨眼,现在我们来稍微修改下 <code>print_it</code> 函数:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::fmt::Debug;
|
|
|
|
|
|
|
|
|
|
fn print_it<T: Debug + 'static>( input: &T) {
|
|
|
|
|
println!( "'static value passed in is: {:?}", input );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let i = 5;
|
|
|
|
|
|
|
|
|
|
print_it(&i);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>这段代码竟然不报错了!原因在于我们约束的是 <code>T</code>,但是使用的却是它的引用 <code>&T</code>,换而言之,我们根本没有直接使用 <code>T</code>,因此编译器就没有去检查 <code>T</code> 的生命周期约束!它只要确保 <code>&T</code> 的生命周期符合规则即可,在上面代码中,它自然是符合的。</p>
|
|
|
|
|
<p>再来看一个例子:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::fmt::Display;
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let r1;
|
|
|
|
|
let r2;
|
|
|
|
|
{
|
|
|
|
|
static STATIC_EXAMPLE: i32 = 42;
|
|
|
|
|
r1 = &STATIC_EXAMPLE;
|
|
|
|
|
let x = "&'static str";
|
|
|
|
|
r2 = x;
|
|
|
|
|
// r1 和 r2 持有的数据都是 'static 的,因此在花括号结束后,并不会被释放
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
println!("&'static i32: {}", r1); // -> 42
|
|
|
|
|
println!("&'static str: {}", r2); // -> &'static str
|
|
|
|
|
|
|
|
|
|
let r3: &str;
|
|
|
|
|
|
|
|
|
|
{
|
|
|
|
|
let s1 = "String".to_string();
|
|
|
|
|
|
|
|
|
|
// s1 虽然没有 'static 生命周期,但是它依然可以满足 T: 'static 的约束
|
|
|
|
|
// 充分说明这个约束是多么的弱。。
|
|
|
|
|
static_bound(&s1);
|
|
|
|
|
|
|
|
|
|
// s1 是 String 类型,没有 'static 的生命周期,因此下面代码会报错
|
|
|
|
|
r3 = &s1;
|
|
|
|
|
|
|
|
|
|
// s1 在这里被 drop
|
|
|
|
|
}
|
|
|
|
|
println!("{}", r3);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn static_bound<T: Display + 'static>(t: &T) {
|
|
|
|
|
println!("{}", t);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<h2 id="static-到底针对谁"><a class="header" href="#static-到底针对谁">static 到底针对谁?</a></h2>
|
|
|
|
|
<p>大家有没有想过,到底是 <code>&'static</code> 这个引用还是该引用指向的数据活得跟程序一样久呢?</p>
|
|
|
|
|
<p><strong>答案是引用指向的数据</strong>,而引用本身是要遵循其作用域范围的,我们来简单验证下:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
{
|
|
|
|
|
let static_string = "I'm in read-only memory";
|
|
|
|
|
println!("static_string: {}", static_string);
|
|
|
|
|
|
|
|
|
|
// 当 `static_string` 超出作用域时,该引用不能再被使用,但是数据依然会存在于 binary 所占用的内存中
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
println!("static_string reference remains alive: {}", static_string);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>以上代码不出所料会报错,原因在于虽然字符串字面量 "I'm in read-only memory" 的生命周期是 <code>'static</code>,但是持有它的引用并不是,它的作用域在内部花括号 <code>}</code> 处就结束了。</p>
|
|
|
|
|
<h2 id="课后练习"><a class="header" href="#课后练习">课后练习</a></h2>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p><a href="https://practice-zh.course.rs/lifetime/static.html">Rust By Practice</a>,支持代码在线编辑和运行,并提供详细的习题解答。(本节暂无习题解答)</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<h2 id="总结"><a class="header" href="#总结">总结</a></h2>
|
|
|
|
|
<p>总之, <code>&'static</code> 和 <code>T: 'static</code> 大体上相似,相比起来,后者的使用形式会更加复杂一些。</p>
|
|
|
|
|
<p>至此,相信大家对于 <code>'static</code> 和 <code>T: 'static</code> 也有了清晰的理解,那么我们应该如何使用它们呢?</p>
|
|
|
|
|
<p>作为经验之谈,可以这么来:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li>如果你需要添加 <code>&'static</code> 来让代码工作,那很可能是设计上出问题了</li>
|
|
|
|
|
<li>如果你希望满足和取悦编译器,那就使用 <code>T: 'static</code>,很多时候它都能解决问题</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p>一个小知识,在 Rust 标准库中,有 48 处用到了 &'static ,112 处用到了 <code>T: 'static</code> ,看来取悦编译器不仅仅是菜鸟需要的,高手也经常用到 :)</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
|
|
|
|
|
<div id="giscus-container"></div>
|
|
|
|
|
</main>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
|
<a rel="prev" href="../../advance/lifetime/advance.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/functional-programing/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="../../advance/lifetime/advance.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/functional-programing/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>
|
|
|
|
|
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/static.md"
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
|
|
<script src="../../assets/custom.js"></script>
|
|
|
|
|
<script src="../../assets/bigPicture.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|