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.

565 lines
80 KiB

4 months ago
<!DOCTYPE HTML>
<html lang="zh-CN" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>特征对象 - Rust语言圣经(Rust Course)</title>
<!-- Custom HTML head -->
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="../../favicon.svg">
<link rel="shortcut icon" href="../../favicon.png">
<link rel="stylesheet" href="../../css/variables.css">
<link rel="stylesheet" href="../../css/general.css">
<link rel="stylesheet" href="../../css/chrome.css">
<link rel="stylesheet" href="../../css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="../../fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="../../highlight.css">
<link rel="stylesheet" href="../../tomorrow-night.css">
<link rel="stylesheet" href="../../ayu-highlight.css">
<!-- Custom theme stylesheets -->
<link rel="stylesheet" href="../../theme/style.css">
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "../../";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item affix "><a href="../../about-book.html">关于本书</a></li><li class="chapter-item affix "><a href="../../into-rust.html">进入 Rust 编程世界</a></li><li class="chapter-item affix "><a href="../../first-try/sth-you-should-not-do.html">避免从入门到放弃</a></li><li class="chapter-item affix "><a href="../../community.html">社区和锈书</a></li><li class="spacer"></li><li class="chapter-item affix "><a href="../../some-thoughts.html">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 expanded "><a href="../../basic/intro.html"><strong aria-hidden="true">2.</strong> Rust 基础入门</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/variable.html"><strong aria-hidden="true">2.1.</strong> 变量绑定与解构</a></li><li class="chapter-item "><a href="../../basic/base-type/index.html"><strong aria-hidden="true">2.2.</strong> 基本类型</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/base-type/numbers.html"><strong aria-hidden="true">2.2.1.</strong> 数值类型</a></li><li class="chapter-item "><a href="../../basic/base-type/char-bool.html"><strong aria-hidden="true">2.2.2.</strong> 字符、布尔、单元类型</a></li><li class="chapter-item "><a href="../../basic/base-type/statement-expression.html"><strong aria-hidden="true">2.2.3.</strong> 语句与表达式</a></li><li class="chapter-item "><a href="../../basic/base-type/function.html"><strong aria-hidden="true">2.2.4.</strong> 函数</a></li></ol></li><li class="chapter-item "><a href="../../basic/ownership/index.html"><strong aria-hidden="true">2.3.</strong> 所有权和借用</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/ownership/ownership.html"><strong aria-hidden="true">2.3.1.</strong> 所有权</a></li><li class="chapter-item "><a href="../../basic/ownership/borrowing.html"><strong aria-hidden="true">2.3.2.</strong> 引用与借用</a></li></ol></li><li class="chapter-item "><a href="../../basic/compound-type/intro.html"><strong aria-hidden="true">2.4.</strong> 复合类型</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/compound-type/string-slice.html"><strong aria-hidden="true">2.4.1.</strong> 字符串与切片</a></li><li class="chapter-item "><a href="../../basic/compound-type/tuple.html"><strong aria-hidden="true">2.4.2.</strong> 元组</a></li><li class="chapter-item "><a href="../../basic/compound-type/struct.html"><strong aria-hidden="true">2.4.3.</strong> 结构体</a></li><li class="chapter-item "><a href="../../basic/compound-type/enum.html"><strong aria-hidden="true">2.4.4.</strong> 枚举</a></li><li class="chapter-item "><a href="../../basic/compound-type/array.html"><strong aria-hidden="true">2.4.5.</strong><>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Rust语言圣经(Rust Course)</h1>
<div class="right-buttons">
<a href="../../print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/sunface/rust-course" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
<a href="https://github.com/sunface/rust-course/edit/main/src/basic/trait/trait-object.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>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn returns_summarizable(switch: bool) -&gt; impl Summary {
if switch {
Post {
// ...
}
} else {
Weibo {
// ...
}
}
}
<span class="boring">}</span></code></pre></pre>
<p>其中 <code>Post</code><code>Weibo</code> 都实现了 <code>Summary</code> 特征,因此上面的函数试图通过返回 <code>impl Summary</code> 来返回这两个类型,但是编译器却无情地报错了,原因是 <code>impl Trait</code> 的返回值类型并不支持多种不同的类型返回,那如果我们想返回多种类型,该怎么办?</p>
<p>再来考虑一个问题:现在在做一款游戏,需要将多个对象渲染在屏幕上,这些对象属于不同的类型,存储在列表中,渲染的时候,需要循环该列表并顺序渲染每个对象,在 Rust 中该怎么实现?</p>
<p>聪明的同学可能已经能想到一个办法,利用枚举:</p>
<pre><pre class="playground"><code class="language-rust edition2021">#[derive(Debug)]
enum UiObject {
Button,
SelectBox,
}
fn main() {
let objects = [
UiObject::Button,
UiObject::SelectBox
];
for o in objects {
draw(o)
}
}
fn draw(o: UiObject) {
println!(&quot;{:?}&quot;,o);
}</code></pre></pre>
<p>Bingo这个确实是一个办法但是问题来了如果你的对象集合并不能事先明确地知道呢或者别人想要实现一个 UI 组件呢?此时枚举中的类型是有些缺少的,是不是还要修改你的代码增加一个枚举成员?</p>
<p>总之,在编写这个 UI 库时,我们无法知道所有的 UI 对象类型,只知道的是:</p>
<ul>
<li>UI 对象的类型不同</li>
<li>需要一个统一的类型来处理这些对象,无论是作为函数参数还是作为列表中的一员</li>
<li>需要对每一个对象调用 <code>draw</code> 方法</li>
</ul>
<p>在拥有继承的语言中,可以定义一个名为 <code>Component</code> 的类,该类上有一个 <code>draw</code> 方法。其他的类比如 <code>Button</code><code>Image</code><code>SelectBox</code> 会从 <code>Component</code> 派生并因此继承 <code>draw</code> 方法。它们各自都可以覆盖 <code>draw</code> 方法来定义自己的行为,但是框架会把所有这些类型当作是 <code>Component</code> 的实例,并在其上调用 <code>draw</code>。不过 Rust 并没有继承,我们得另寻出路。</p>
<h2 id="特征对象定义"><a class="header" href="#特征对象定义">特征对象定义</a></h2>
<p>为了解决上面的所有问题Rust 引入了一个概念 —— <strong>特征对象</strong></p>
<p>在介绍特征对象之前,先来为之前的 UI 组件定义一个特征:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait Draw {
fn draw(&amp;self);
}
<span class="boring">}</span></code></pre></pre>
<p>只要组件实现了 <code>Draw</code> 特征,就可以调用 <code>draw</code> 方法来进行渲染。假设有一个 <code>Button</code><code>SelectBox</code> 组件实现了 <code>Draw</code> 特征:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct Button {
pub width: u32,
pub height: u32,
pub label: String,
}
impl Draw for Button {
fn draw(&amp;self) {
// 绘制按钮的代码
}
}
struct SelectBox {
width: u32,
height: u32,
options: Vec&lt;String&gt;,
}
impl Draw for SelectBox {
fn draw(&amp;self) {
// 绘制SelectBox的代码
}
}
<span class="boring">}</span></code></pre></pre>
<p>此时,还需要一个动态数组来存储这些 UI 对象:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct Screen {
pub components: Vec&lt;?&gt;,
}
<span class="boring">}</span></code></pre></pre>
<p>注意到上面代码中的 <code>?</code> 吗?它的意思是:我们应该填入什么类型,可以说就之前学过的内容里,你找不到哪个类型可以填入这里,但是因为 <code>Button</code><code>SelectBox</code> 都实现了 <code>Draw</code> 特征,那我们是不是可以把 <code>Draw</code> 特征的对象作为类型,填入到数组中呢?答案是肯定的。</p>
<p><strong>特征对象</strong>指向实现了 <code>Draw</code> 特征的类型的实例,也就是指向了 <code>Button</code> 或者 <code>SelectBox</code> 的实例,这种映射关系是存储在一张表中,可以在运行时通过特征对象找到具体调用的类型方法。</p>
<p>可以通过 <code>&amp;</code> 引用或者 <code>Box&lt;T&gt;</code> 智能指针的方式来创建特征对象。</p>
<blockquote>
<p><code>Box&lt;T&gt;</code> 在后面章节会<a href="https://course.rs/advance/smart-pointer/box.html">详细讲解</a>,大家现在把它当成一个引用即可,只不过它包裹的值会被强制分配在堆上。</p>
</blockquote>
<pre><pre class="playground"><code class="language-rust edition2021">trait Draw {
fn draw(&amp;self) -&gt; String;
}
impl Draw for u8 {
fn draw(&amp;self) -&gt; String {
format!(&quot;u8: {}&quot;, *self)
}
}
impl Draw for f64 {
fn draw(&amp;self) -&gt; String {
format!(&quot;f64: {}&quot;, *self)
}
}
// 若 T 实现了 Draw 特征, 则调用该函数时传入的 Box&lt;T&gt; 可以被隐式转换成函数参数签名中的 Box&lt;dyn Draw&gt;
fn draw1(x: Box&lt;dyn Draw&gt;) {
// 由于实现了 Deref 特征Box 智能指针会自动解引用为它所包裹的值,然后调用该值对应的类型上定义的 `draw` 方法
x.draw();
}
fn draw2(x: &amp;dyn Draw) {
x.draw();
}
fn main() {
let x = 1.1f64;
// do_something(&amp;x);
let y = 8u8;
// x 和 y 的类型 T 都实现了 `Draw` 特征,因为 Box&lt;T&gt; 可以在函数调用时隐式地被转换为特征对象 Box&lt;dyn Draw&gt;
// 基于 x 的值创建一个 Box&lt;f64&gt; 类型的智能指针,指针指向的数据被放置在了堆上
draw1(Box::new(x));
// 基于 y 的值创建一个 Box&lt;u8&gt; 类型的智能指针
draw1(Box::new(y));
draw2(&amp;x);
draw2(&amp;y);
}</code></pre></pre>
<p>上面代码,有几个非常重要的点:</p>
<ul>
<li><code>draw1</code> 函数的参数是 <code>Box&lt;dyn Draw&gt;</code> 形式的特征对象,该特征对象是通过 <code>Box::new(x)</code> 的方式创建的</li>
<li><code>draw2</code> 函数的参数是 <code>&amp;dyn Draw</code> 形式的特征对象,该特征对象是通过 <code>&amp;x</code> 的方式创建的</li>
<li><code>dyn</code> 关键字只用在特征对象的类型声明上,在创建时无需使用 <code>dyn</code></li>
</ul>
<p>因此,可以使用特征对象来代表泛型或具体的类型。</p>
<p>继续来完善之前的 UI 组件代码,首先来实现 <code>Screen</code></p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct Screen {
pub components: Vec&lt;Box&lt;dyn Draw&gt;&gt;,
}
<span class="boring">}</span></code></pre></pre>
<p>其中存储了一个动态数组,里面元素的类型是 <code>Draw</code> 特征对象:<code>Box&lt;dyn Draw&gt;</code>,任何实现了 <code>Draw</code> 特征的类型,都可以存放其中。</p>
<p>再来为 <code>Screen</code> 定义 <code>run</code> 方法,用于将列表中的 UI 组件渲染在屏幕上:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl Screen {
pub fn run(&amp;self) {
for component in self.components.iter() {
component.draw();
}
}
}
<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>pub struct Screen&lt;T: Draw&gt; {
pub components: Vec&lt;T&gt;,
}
impl&lt;T&gt; Screen&lt;T&gt;
where T: Draw {
pub fn run(&amp;self) {
for component in self.components.iter() {
component.draw();
}
}
}
<span class="boring">}</span></code></pre></pre>
<p>上面的 <code>Screen</code> 的列表中,存储了类型为 <code>T</code> 的元素,然后在 <code>Screen</code> 中使用特征约束让 <code>T</code> 实现了 <code>Draw</code> 特征,进而可以调用 <code>draw</code> 方法。</p>
<p>但是这种写法限制了 <code>Screen</code> 实例的 <code>Vec&lt;T&gt;</code> 中的每个元素必须是 <code>Button</code> 类型或者全是 <code>SelectBox</code> 类型。如果只需要同质(相同类型)集合,更倾向于采用泛型+特征约束这种写法,因其实现更清晰,且性能更好(特征对象,需要在运行时从 <code>vtable</code> 动态查找需要调用的方法)。</p>
<p>现在来运行渲染下咱们精心设计的 UI 组件列表:</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let screen = Screen {
components: vec![
Box::new(SelectBox {
width: 75,
height: 10,
options: vec![
String::from(&quot;Yes&quot;),
String::from(&quot;Maybe&quot;),
String::from(&quot;No&quot;)
],
}),
Box::new(Button {
width: 50,
height: 10,
label: String::from(&quot;OK&quot;),
}),
],
};
screen.run();
}</code></pre></pre>
<p>上面使用 <code>Box::new(T)</code> 的方式来创建了两个 <code>Box&lt;dyn Draw&gt;</code> 特征对象,如果以后还需要增加一个 UI 组件,那么让该组件实现 <code>Draw</code> 特征,则可以很轻松的将其渲染在屏幕上,甚至用户可以引入我们的库作为三方库,然后在自己的库中为自己的类型实现 <code>Draw</code> 特征,然后进行渲染。</p>
<p>在动态类型语言中,有一个很重要的概念:<strong>鸭子类型</strong>(<em>duck typing</em>),简单来说,就是只关心值长啥样,而不关心它实际是什么。当一个东西走起来像鸭子,叫起来像鸭子,那么它就是一只鸭子,就算它实际上是一个奥特曼,也不重要,我们就当它是鸭子。</p>
<p>在上例中,<code>Screen</code><code>run</code> 的时候,我们并不需要知道各个组件的具体类型是什么。它也不检查组件到底是 <code>Button</code> 还是 <code>SelectBox</code> 的实例,只要它实现了 <code>Draw</code> 特征,就能通过 <code>Box::new</code> 包装成 <code>Box&lt;dyn Draw&gt;</code> 特征对象,然后被渲染在屏幕上。</p>
<p>使用特征对象和 Rust 类型系统来进行类似鸭子类型操作的优势是,无需在运行时检查一个值是否实现了特定方法或者担心在调用时因为值没有实现方法而产生错误。如果值没有实现特征对象所需的特征, 那么 Rust 根本就不会编译这些代码:</p>
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
let screen = Screen {
components: vec![
Box::new(String::from(&quot;Hi&quot;)),
],
};
screen.run();
}</code></pre></pre>
<p>因为 <code>String</code> 类型没有实现 <code>Draw</code> 特征,编译器直接就会报错,不会让上述代码运行。如果想要 <code>String</code> 类型被渲染在屏幕上,那么只需要为其实现 <code>Draw</code> 特征即可,非常容易。</p>
<!-- #### &dyn 和 Box\<dyn\>的区别
前文提到, `&dyn` 和 `Box<dyn>` 都可以用于特征对象,因此在功能上 `&dyn` 和 `Box<dyn>` 几乎没有区别,唯一的区别就是:`&dyn` 减少了一次指针调用。
因为 `Box<dyn>` 是一个宽指针(`fat pointer`),它需要一次额外的解引用后,才能获取到指向 `vtable` 的指针,然后再通过该指针访问 `vtable` 查询到具体的函数指针,最后进行调用。
所以,如果你在乎性能,又想使用特征对象简化代码,可以优先考虑 `&dyn`。 -->
<p>注意 <code>dyn</code> 不能单独作为特征对象的定义,例如下面的代码编译器会报错,原因是特征对象可以是任意实现了某个特征的类型,编译器在编译期不知道该类型的大小,不同的类型大小是不同的。</p>
<p><code>&amp;dyn</code><code>Box&lt;dyn&gt;</code> 在编译期都是已知大小,所以可以用作特征对象的定义。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn draw2(x: dyn Draw) {
x.draw();
}
<span class="boring">}</span></code></pre></pre>
<pre><code>10 | fn draw2(x: dyn Draw) {
| ^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `(dyn Draw + 'static)`
help: function arguments must have a statically known size, borrowed types always have a known size
</code></pre>
<h2 id="特征对象的动态分发"><a class="header" href="#特征对象的动态分发">特征对象的动态分发</a></h2>
<p>回忆一下泛型章节我们提到过的,泛型是在编译期完成处理的:编译器会为每一个泛型参数对应的具体类型生成一份代码,这种方式是<strong>静态分发(static dispatch)</strong>,因为是在编译期完成的,对于运行期性能完全没有任何影响。</p>
<p>与静态分发相对应的是<strong>动态分发(dynamic dispatch)</strong>,在这种情况下,直到运行时,才能确定需要调用什么方法。之前代码中的关键字 <code>dyn</code> 正是在强调这一“动态”的特点。</p>
<p>当使用特征对象时Rust 必须使用动态分发。编译器无法知晓所有可能用于特征对象代码的类型所以它也不知道应该调用哪个类型的哪个方法实现。为此Rust 在运行时使用特征对象中的指针来知晓需要调用哪个方法。动态分发也阻止编译器有选择的内联方法代码,这会相应的禁用一些优化。</p>
<p>下面这张图很好的解释了静态分发 <code>Box&lt;T&gt;</code> 和动态分发 <code>Box&lt;dyn Trait&gt;</code> 的区别:</p>
<img alt="" src="https://pic1.zhimg.com/80/v2-b771fe4cfc6ebd63d9aff42840eb8e67_1440w.jpg" class="center" />
<p>结合上文的内容和这张图可以了解:</p>
<ul>
<li><strong>特征对象大小不固定</strong>:这是因为,对于特征 <code>Draw</code>,类型 <code>Button</code> 可以实现特征 <code>Draw</code>,类型 <code>SelectBox</code> 也可以实现特征 <code>Draw</code>,因此特征没有固定大小</li>
<li><strong>几乎总是使用特征对象的引用方式</strong>,如 <code>&amp;dyn Draw</code><code>Box&lt;dyn Draw&gt;</code>
<ul>
<li>虽然特征对象没有固定大小,但它的引用类型的大小是固定的,它由两个指针组成(<code>ptr</code><code>vptr</code>),因此占用两个指针大小</li>
<li>一个指针 <code>ptr</code> 指向实现了特征 <code>Draw</code> 的具体类型的实例,也就是当作特征 <code>Draw</code> 来用的类型的实例,比如类型 <code>Button</code> 的实例、类型 <code>SelectBox</code> 的实例</li>
<li>另一个指针 <code>vptr</code> 指向一个虚表 <code>vtable</code><code>vtable</code> 中保存了类型 <code>Button</code> 或类型 <code>SelectBox</code> 的实例对于可以调用的实现于特征 <code>Draw</code> 的方法。当调用方法时,直接从 <code>vtable</code> 中找到方法并调用。之所以要使用一个 <code>vtable</code> 来保存各实例的方法,是因为实现了特征 <code>Draw</code> 的类型有多种,这些类型拥有的方法各不相同,当将这些类型的实例都当作特征 <code>Draw</code> 来使用时(此时,它们全都看作是特征 <code>Draw</code> 类型的实例),有必要区分这些实例各自有哪些方法可调用</li>
</ul>
</li>
</ul>
<p>简而言之,当类型 <code>Button</code> 实现了特征 <code>Draw</code> 时,类型 <code>Button</code> 的实例对象 <code>btn</code> 可以当作特征 <code>Draw</code> 的特征对象类型来使用,<code>btn</code> 中保存了作为特征对象的数据指针(指向类型 <code>Button</code> 的实例数据)和行为指针(指向 <code>vtable</code>)。</p>
<p>一定要注意,此时的 <code>btn</code><code>Draw</code> 的特征对象的实例,而不再是具体类型 <code>Button</code> 的实例,而且 <code>btn</code><code>vtable</code> 只包含了实现自特征 <code>Draw</code> 的那些方法(比如 <code>draw</code>),因此 <code>btn</code> 只能调用实现于特征 <code>Draw</code><code>draw</code> 方法,而不能调用类型 <code>Button</code> 本身实现的方法和类型 <code>Button</code> 实现于其他特征的方法。<strong>也就是说,<code>btn</code> 是哪个特征对象的实例,它的 <code>vtable</code> 中就包含了该特征的方法。</strong></p>
<h2 id="self-与-self"><a class="header" href="#self-与-self">Self 与 self</a></h2>
<p>在 Rust 中,有两个<code>self</code>,一个指代当前的实例对象,一个指代特征或者方法类型的别名:</p>
<pre><pre class="playground"><code class="language-rust edition2021">trait Draw {
fn draw(&amp;self) -&gt; Self;
}
#[derive(Clone)]
struct Button;
impl Draw for Button {
fn draw(&amp;self) -&gt; Self {
return self.clone()
}
}
fn main() {
let button = Button;
let newb = button.draw();
}</code></pre></pre>
<p>上述代码中,<code>self</code>指代的就是当前的实例对象,也就是 <code>button.draw()</code> 中的 <code>button</code> 实例,<code>Self</code> 则指代的是 <code>Button</code> 类型。</p>
<p>当理解了 <code>self</code><code>Self</code> 的区别后,我们再来看看何为对象安全。</p>
<h2 id="特征对象的限制"><a class="header" href="#特征对象的限制">特征对象的限制</a></h2>
<p>不是所有特征都能拥有特征对象,只有对象安全的特征才行。当一个特征的所有方法都有如下属性时,它的对象才是安全的:</p>
<ul>
<li>方法的返回类型不能是 <code>Self</code></li>
<li>方法没有任何泛型参数</li>
</ul>
<p>对象安全对于特征对象是必须的,因为一旦有了特征对象,就不再需要知道实现该特征的具体类型是什么了。如果特征方法返回了具体的 <code>Self</code> 类型,但是特征对象忘记了其真正的类型,那这个 <code>Self</code> 就非常尴尬,因为没人知道它是谁了。但是对于泛型类型参数来说,当使用特征时其会放入具体的类型参数:此具体类型变成了实现该特征的类型的一部分。而当使用特征对象时其具体类型被抹去了,故而无从得知放入泛型参数类型到底是什么。</p>
<p>标准库中的 <code>Clone</code> 特征就不符合对象安全的要求:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait Clone {
fn clone(&amp;self) -&gt; Self;
}
<span class="boring">}</span></code></pre></pre>
<p>因为它的其中一个方法,返回了 <code>Self</code> 类型,因此它是对象不安全的。</p>
<p><code>String</code> 类型实现了 <code>Clone</code> 特征, <code>String</code> 实例上调用 <code>clone</code> 方法时会得到一个 <code>String</code> 实例。类似的,当调用 <code>Vec&lt;T&gt;</code> 实例的 <code>clone</code> 方法会得到一个 <code>Vec&lt;T&gt;</code> 实例。<code>clone</code> 的签名需要知道什么类型会代替 <code>Self</code>,因为这是它的返回值。</p>
<p>如果违反了对象安全的规则,编译器会提示你。例如,如果尝试使用之前的 <code>Screen</code> 结构体来存放实现了 <code>Clone</code> 特征的类型:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct Screen {
pub components: Vec&lt;Box&lt;dyn Clone&gt;&gt;,
}
<span class="boring">}</span></code></pre></pre>
<p>将会得到如下错误:</p>
<pre><code class="language-text">error[E0038]: the trait `std::clone::Clone` cannot be made into an object
--&gt; src/lib.rs:2:5
|
2 | pub components: Vec&lt;Box&lt;dyn Clone&gt;&gt;,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::clone::Clone`
cannot be made into an object
|
= note: the trait cannot require that `Self : Sized`
</code></pre>
<p>这意味着不能以这种方式使用此特征作为特征对象。</p>
<h2 id="课后练习"><a class="header" href="#课后练习">课后练习</a></h2>
<blockquote>
<p><a href="https://practice-zh.course.rs/generics-traits/trait-object.html">Rust By Practice</a>,支持代码在线编辑和运行,并提供详细的<a href="https://github.com/sunface/rust-by-practice/blob/master/solutions/generics-traits/trait-object.md">习题解答</a></p>
</blockquote>
<div id="giscus-container"></div>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../../basic/trait/trait.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="../../basic/trait/advance-trait.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="../../basic/trait/trait.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="../../basic/trait/advance-trait.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="../../ace.js"></script>
<script src="../../editor.js"></script>
<script src="../../mode-rust.js"></script>
<script src="../../theme-dawn.js"></script>
<script src="../../theme-tomorrow_night.js"></script>
<script src="../../elasticlunr.min.js"></script>
<script src="../../mark.min.js"></script>
<script src="../../searcher.js"></script>
<script src="../../clipboard.min.js"></script>
<script src="../../highlight.js"></script>
<script src="../../book.js"></script>
<script type="text/javascript" charset="utf-8">
var pagePath = "basic/trait/trait-object.md"
</script>
<!-- Custom JS scripts -->
<script src="../../assets/custom.js"></script>
<script src="../../assets/bigPicture.js"></script>
</div>
</body>
</html>