|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="en" class="light" dir="ltr">
|
|
|
|
|
<head>
|
|
|
|
|
<!-- Book generated using mdBook -->
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>面向对象语言的特点 - Rust 程序设计语言 简体中文版</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="ferris.css">
|
|
|
|
|
<link rel="stylesheet" href="theme/2018-edition.css">
|
|
|
|
|
<link rel="stylesheet" href="theme/semantic-notes.css">
|
|
|
|
|
<link rel="stylesheet" href="theme/listing.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 expanded affix "><a href="title-page.html">Rust 程序设计语言</a></li><li class="chapter-item expanded affix "><a href="foreword.html">前言</a></li><li class="chapter-item expanded affix "><a href="ch00-00-introduction.html">简介</a></li><li class="chapter-item expanded "><a href="ch01-00-getting-started.html"><strong aria-hidden="true">1.</strong> 入门指南</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch01-01-installation.html"><strong aria-hidden="true">1.1.</strong> 安装</a></li><li class="chapter-item expanded "><a href="ch01-02-hello-world.html"><strong aria-hidden="true">1.2.</strong> Hello, World!</a></li><li class="chapter-item expanded "><a href="ch01-03-hello-cargo.html"><strong aria-hidden="true">1.3.</strong> Hello, Cargo!</a></li></ol></li><li class="chapter-item expanded "><a href="ch02-00-guessing-game-tutorial.html"><strong aria-hidden="true">2.</strong> 写个猜数字游戏</a></li><li class="chapter-item expanded "><a href="ch03-00-common-programming-concepts.html"><strong aria-hidden="true">3.</strong> 常见编程概念</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch03-01-variables-and-mutability.html"><strong aria-hidden="true">3.1.</strong> 变量与可变性</a></li><li class="chapter-item expanded "><a href="ch03-02-data-types.html"><strong aria-hidden="true">3.2.</strong> 数据类型</a></li><li class="chapter-item expanded "><a href="ch03-03-how-functions-work.html"><strong aria-hidden="true">3.3.</strong> 函数</a></li><li class="chapter-item expanded "><a href="ch03-04-comments.html"><strong aria-hidden="true">3.4.</strong> 注释</a></li><li class="chapter-item expanded "><a href="ch03-05-control-flow.html"><strong aria-hidden="true">3.5.</strong> 控制流</a></li></ol></li><li class="chapter-item expanded "><a href="ch04-00-understanding-ownership.html"><strong aria-hidden="true">4.</strong> 认识所有权</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch04-01-what-is-ownership.html"><strong aria-hidden="true">4.1.</strong> 什么是所有权?</a></li><li class="chapter-item expanded "><a href="ch04-02-references-and-borrowing.html"><strong aria-hidden="true">4.2.</strong> 引用与借用</a></li><li class="chapter-item expanded "><a href="ch04-03-slices.html"><strong aria-hidden="true">4.3.</strong> Slice 类型</a></li></ol></li><li class="chapter-item expanded "><a href="ch05-00-structs.html"><strong aria-hidden="true">5.</strong> 使用结构体组织相关联的数据</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch05-01-defining-structs.html"><strong aria-hidden="true">5.1.</strong> 结构体的定义和实例化</a></li><li class="chapter-item expanded "><a href="ch05-02-example-structs.html"><strong aria-hidden="true">5.2.</strong> 结构体示例程序</a></li><li class="chapter-item expanded "><a href="ch05-03-method-syntax.html"><strong aria-hidden="true">5.3.</strong> 方法语法</a></li></ol></li><li class="chapter-item expanded "><a href="ch06-00-enums.html"><strong aria-hidden="true">6.</strong> 枚举和模式匹配</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch06-01-defining-an-enum.html"><strong aria-hidden="true">6.1.</strong> 枚举的定义</a></li><li class="chapter-item expanded "><a href="ch06-02-match.html"><strong aria-hidden="true">6.2.</strong> match 控制流结构</a></li><li class="chapter-item expanded "><a href="ch06-03-if-let.html"><strong aria-hidden="true">6.3.</strong> if let 简洁控制流</a></li></ol></li><li class="chapter-item expanded "><a href="ch07-00-managing-growing-projects-with-packages-crates-and-modules.html"><strong aria-hidden="true">7.</strong> 使用包、Crate 和模块管理不断增长的项目</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ch07-01-packages-and-crates.html"><strong aria-hidden="true">7.1.</strong> 包和 Crate</a></li><li class="chapter-item expanded "><a h
|
|
|
|
|
</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 程序设计语言 简体中文版</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/KaiserY/trpl-zh-cn/tree/main" title="Git repository" aria-label="Git repository">
|
|
|
|
|
<i id="git-repository-button" class="fa fa-github"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a href="https://github.com/KaiserY/trpl-zh-cn/edit/main/src/ch18-01-what-is-oo.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">
|
|
|
|
|
<main>
|
|
|
|
|
<h2 id="面向对象语言的特征"><a class="header" href="#面向对象语言的特征">面向对象语言的特征</a></h2>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p><a href="https://github.com/rust-lang/book/blob/main/src/ch18-01-what-is-oo.md">ch18-01-what-is-oo.md</a>
|
|
|
|
|
<br>
|
|
|
|
|
commit 398d6f48d2e6b7b15efd51c4541d446e89de3892</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<p>关于一门语言必须具备哪些特征才能被视为面向对象,目前在编程社区中并没有共识。Rust 受到了许多编程范式的影响,包括面向对象编程(OOP);例如,在第 13 章中,我们探讨了来自函数式编程的特性。可以说,面向对象的语言共有一些共同的特征,即对象、封装和继承。我们将会讨论这些特征分别是什么,以及 Rust 是否支持它们。</p>
|
|
|
|
|
<h3 id="对象包含数据和行为"><a class="header" href="#对象包含数据和行为">对象包含数据和行为</a></h3>
|
|
|
|
|
<p>由 Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides(Addison-Wesley Professional, 1994)编写的书 <em>Design Patterns: Elements of Reusable Object-Oriented Software</em> ,通称 <em>The Gang of Four</em> (“四人帮”),是一本面向对象设计模式的目录。它这样定义面向对象编程:</p>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p>Object-oriented programs are made up of objects. An <em>object</em> packages both
|
|
|
|
|
data and the procedures that operate on that data. The procedures are
|
|
|
|
|
typically called <em>methods</em> or <em>operations</em>.</p>
|
|
|
|
|
<p>面向对象的程序由对象组成。一个 <strong>对象</strong> 包含数据和操作这些数据的过程。这些过程通常被称为 <strong>方法</strong> 或 <strong>操作</strong>。</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<p>在这个定义下,Rust 是面向对象的:结构体和枚举包含数据而 <code>impl</code> 块提供了在结构体和枚举之上的方法。虽然带有方法的结构体和枚举并不被 <strong>称为</strong> 对象,但是它们提供了与对象相同的功能,参考 <em>The Gang of Four</em> 中对象的定义。</p>
|
|
|
|
|
<h3 id="封装隐藏了实现细节"><a class="header" href="#封装隐藏了实现细节">封装隐藏了实现细节</a></h3>
|
|
|
|
|
<p>另一个通常与面向对象编程关联的概念是 <strong>封装</strong>(<em>encapsulation</em>):一个对象的实现细节对使用该对象的代码不可访问。因此,对象交互的唯一方式是通过其公共 API;使用对象的代码不应能直接触及对象的内部并改变数据或行为。这使得程序员能够更改和重构一个对象的内部实现,而无需改变使用该对象的代码。</p>
|
|
|
|
|
<p>我们在第 7 章讨论了如何控制封装:我们可以使用 <code>pub</code> 关键字来决定代码中的哪些模块、类型、函数和方法是公有的,而默认情况下其他所有内容都是私有的。例如,我们可以定义一个 <code>AveragedCollection</code> 结构体,其中有一个存有 <code>Vec<i32></code> 的字段。该结构体还可以有一个字段存储其平均值,以便需要时取用。示例 17-1 给出了 <code>AveragedCollection</code> 结构体的定义:</p>
|
|
|
|
|
<p><span class="filename">文件名:src/lib.rs</span></p>
|
|
|
|
|
<pre><code class="language-rust noplayground">pub struct AveragedCollection {
|
|
|
|
|
list: Vec<i32>,
|
|
|
|
|
average: f64,
|
|
|
|
|
}</code></pre>
|
|
|
|
|
<p><span class="caption">示例 17-1: <code>AveragedCollection</code> 结构体维护了一个整型列表及其所有元素的平均值。</span></p>
|
|
|
|
|
<p>该结构体被标记为 <code>pub</code>,这样其他代码就可以使用它,但结构体内的字段保持私有。这在这种情况下很重要,因为我们想确保每当列表中添加或删除值时,平均值也会更新。我们通过实现结构体上的 <code>add</code>、<code>remove</code> 和 <code>average</code> 方法来做到这一点,如示例 17-2 所示:</p>
|
|
|
|
|
<p><span class="filename">文件名:src/lib.rs</span></p>
|
|
|
|
|
<pre><code class="language-rust noplayground"><span class="boring">pub struct AveragedCollection {
|
|
|
|
|
</span><span class="boring"> list: Vec<i32>,
|
|
|
|
|
</span><span class="boring"> average: f64,
|
|
|
|
|
</span><span class="boring">}
|
|
|
|
|
</span><span class="boring">
|
|
|
|
|
</span>impl AveragedCollection {
|
|
|
|
|
pub fn add(&mut self, value: i32) {
|
|
|
|
|
self.list.push(value);
|
|
|
|
|
self.update_average();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn remove(&mut self) -> Option<i32> {
|
|
|
|
|
let result = self.list.pop();
|
|
|
|
|
match result {
|
|
|
|
|
Some(value) => {
|
|
|
|
|
self.update_average();
|
|
|
|
|
Some(value)
|
|
|
|
|
}
|
|
|
|
|
None => None,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn average(&self) -> f64 {
|
|
|
|
|
self.average
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn update_average(&mut self) {
|
|
|
|
|
let total: i32 = self.list.iter().sum();
|
|
|
|
|
self.average = total as f64 / self.list.len() as f64;
|
|
|
|
|
}
|
|
|
|
|
}</code></pre>
|
|
|
|
|
<p><span class="caption">示例 17-2: 在 <code>AveragedCollection</code> 结构体上实现了 <code>add</code>、<code>remove</code> 和 <code>average</code> 公有方法</span></p>
|
|
|
|
|
<p>公有方法 <code>add</code>、<code>remove</code> 和 <code>average</code> 是修改 <code>AveragedCollection</code> 实例的唯一方式。当使用 <code>add</code> 方法把一个元素加入到 <code>list</code> 或者使用 <code>remove</code> 方法来删除时,这些方法的实现同时会调用私有的 <code>update_average</code> 方法来更新 <code>average</code> 字段。</p>
|
|
|
|
|
<p><code>list</code> 和 <code>average</code> 是私有的,所以没有其他方式来使得外部的代码直接向 <code>list</code> 增加或者删除元素,否则 <code>list</code> 改变时可能会导致 <code>average</code> 字段不同步。<code>average</code> 方法返回 <code>average</code> 字段的值,这使得外部的代码只能读取 <code>average</code> 而不能修改它。</p>
|
|
|
|
|
<p>因为我们已经封装了 <code>AveragedCollection</code> 的实现细节,改动数据结构等内部实现非常简单。例如,可以使用 <code>HashSet<i32></code> 代替 <code>Vec<i32></code> 作为 <code>list</code> 字段的类型。只要 <code>add</code>、<code>remove</code> 和 <code>average</code> 这些公有方法的签名保持不变,使用 <code>AveragedCollection</code> 的代码就无需改变。如果我们将 <code>list</code> 设为公有,情况就未必如此: <code>HashSet<i32></code> 和 <code>Vec<i32></code> 使用不同的方法增加或移除项,所以如果外部代码直接修改 <code>list</code> ,很可能需要进行更改。</p>
|
|
|
|
|
<p>如果封装被认为是面向对象语言所必要的特征,那么 Rust 满足这个要求。在代码中不同的部分控制 <code>pub</code> 的使用来封装实现细节。</p>
|
|
|
|
|
<h2 id="继承作为类型系统与代码共享"><a class="header" href="#继承作为类型系统与代码共享">继承,作为类型系统与代码共享</a></h2>
|
|
|
|
|
<p><strong>继承</strong>(<em>Inheritance</em>)是一种机制:一个对象可以从另一个对象的定义中继承元素,从而获得父对象的数据和行为,无需再次定义。</p>
|
|
|
|
|
<p>如果一种语言必须具有继承才能被认为是面向对象语言,那么 Rust 不是其中之一。Rust 不支持定义一个结构体时继承父结构体的字段和方法,除非使用宏。</p>
|
|
|
|
|
<p>然而,如果您习惯于在编程过程中使用继承,那么根据运用继承的原因,Rust 提供了其他解决方案。</p>
|
|
|
|
|
<p>选择继承有两个主要的原因。其一是代码复用:您可以为一种类型实现特定的行为,继承可将其复用到不同的类型上。在 Rust 代码中可以使用默认 trait 方法实现来进行有限的代码复用,就像示例 10-14 中在 <code>Summary</code> trait 上增加的 <code>summarize</code> 方法的默认实现。任何实现了 <code>Summary</code> trait 的类型都可以使用 <code>summarize</code> 方法而无须进一步实现。这类似于父类有一个方法的实现,继承的子类也拥有这个方法的实现。当实现 <code>Summary</code> trait 时也可以选择覆盖 <code>summarize</code> 的默认实现,这类似于子类覆盖从父类继承方法的实现。</p>
|
|
|
|
|
<p>其二与类型系统有关:子类型可以用于父类型被使用的地方。这也被称为 <strong>多态</strong>(<em>polymorphism</em>):如果多个对象共享某些特征,可以在运行时将它们互相替代。</p>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p>多态(Polymorphism)</p>
|
|
|
|
|
<p>对很多人来说,多态性与继承同义。但它实际上是一个更广义的概念,指的是可以处理多种类型数据的代码。对继承而言,这些类型通常是子类。
|
|
|
|
|
Rust 使用泛型来抽象不同可能的类型,并通过 trait bounds 来约束这些类型所必须提供的内容。这有时被称为 <em>bounded parametric polymorphism</em>。</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<p>作为一种语言设计的解决方案,继承在许多新的编程语言中逐渐不被青睐,因为它经常有分享过多代码的风险。子类不应总是共享父类的所有特征,但是继承始终如此。它还引入了在子类上调用方法的可能性,这些方法可能没有意义,或因为方法不适用于子类而导致错误。此外,一些语言只允许单一继承(意味着子类只能从一个类继承),进一步限制了程序设计的灵活性。</p>
|
|
|
|
|
<p>出于这些原因,Rust 使用 trait 对象而非继承。接下来我们会讨论 Rust 如何使用 trait 对象实现多态性。</p>
|
|
|
|
|
|
|
|
|
|
</main>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
|
<a rel="prev" href="ch18-00-oop.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="ch18-02-trait-objects.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="ch18-00-oop.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="ch18-02-trait-objects.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="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>
|
|
|
|
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
|
|
<script src="ferris.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|