|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="en">
|
|
|
|
|
<head>
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>泛型数据类型 - Rust 程序设计语言 简体中文版</title>
|
|
|
|
|
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
|
|
|
|
<meta name="description" content="Rust 程序设计语言 简体中文版">
|
|
|
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
|
|
|
|
|
|
|
|
<base href="">
|
|
|
|
|
|
|
|
|
|
<link rel="stylesheet" href="book.css">
|
|
|
|
|
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
|
|
|
|
|
|
|
|
|
|
<link rel="shortcut icon" href="favicon.png">
|
|
|
|
|
|
|
|
|
|
<!-- Font Awesome -->
|
|
|
|
|
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
|
|
|
|
|
|
|
|
|
|
<link rel="stylesheet" href="highlight.css">
|
|
|
|
|
<link rel="stylesheet" href="tomorrow-night.css">
|
|
|
|
|
|
|
|
|
|
<!-- MathJax -->
|
|
|
|
|
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
|
|
|
|
|
|
|
|
|
<!-- Fetch JQuery from CDN but have a local fallback -->
|
|
|
|
|
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
|
|
|
|
|
<script>
|
|
|
|
|
if (typeof jQuery == 'undefined') {
|
|
|
|
|
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
|
|
|
|
|
}
|
|
|
|
|
</script>
|
|
|
|
|
</head>
|
|
|
|
|
<body class="light">
|
|
|
|
|
<!-- Set the theme before any content is loaded, prevents flash -->
|
|
|
|
|
<script type="text/javascript">
|
|
|
|
|
var theme = localStorage.getItem('theme');
|
|
|
|
|
if (theme == null) { theme = 'light'; }
|
|
|
|
|
$('body').removeClass().addClass(theme);
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
|
|
|
<script type="text/javascript">
|
|
|
|
|
var sidebar = localStorage.getItem('sidebar');
|
|
|
|
|
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
|
|
|
|
|
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<div id="sidebar" class="sidebar">
|
|
|
|
|
<ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> 介绍</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> 安装</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> 猜猜看教程</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> 通用编程概念</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> 变量和可变性</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> 数据类型</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> 函数如何工作</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> 注释</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> 控制流</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> 认识所有权</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> 什么是所有权</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> 引用 & 借用</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> 结构体</a></li><li><ul class="section"><li><a href="ch05-01-method-syntax.html"><strong>5.1.</strong> 方法语法</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> 枚举和模式匹配</a></li><li><ul class="section"><li><a href="ch06-01-defining-an-enum.html"><strong>6.1.</strong> 定义枚举</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> <code>match</code>控制流运算符</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> <code>if let</code>简单控制流</a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> 模块</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code>和文件系统</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> 使用<code>pub</code>控制可见性</a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> 使用<code>use</code>导入命名</a></li></ul></li><li><a href="ch08-00-common-collections.html"><strong>8.</strong> 通用集合类型</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> vector</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> 字符串</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> 哈希 map</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> 错误处理</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> <code>panic!</code>与不可恢复的错误</a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> <code>Result</code>与可恢复的错误</a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> <code>panic!</code>还是不<code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> 泛型、trait 和生命周期</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html" class="active"><strong>10.1.</strong> 泛型数据类型</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> trait:定义共享的行为</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> 生命周期与引用有效性</a></li></ul></li></ul>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div id="page-wrapper" class="page-wrapper">
|
|
|
|
|
|
|
|
|
|
<div class="page">
|
|
|
|
|
<div id="menu-bar" class="menu-bar">
|
|
|
|
|
<div class="left-buttons">
|
|
|
|
|
<i id="sidebar-toggle" class="fa fa-bars"></i>
|
|
|
|
|
<i id="theme-toggle" class="fa fa-paint-brush"></i>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<h1 class="menu-title">Rust 程序设计语言 简体中文版</h1>
|
|
|
|
|
|
|
|
|
|
<div class="right-buttons">
|
|
|
|
|
<i id="print-button" class="fa fa-print" title="Print this book"></i>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div id="content" class="content">
|
|
|
|
|
<a class="header" href="#泛型数据类型" name="泛型数据类型"><h2>泛型数据类型</h2></a>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p><a href="https://github.com/rust-lang/book/blob/master/src/ch10-01-syntax.md">ch10-01-syntax.md</a>
|
|
|
|
|
<br>
|
|
|
|
|
commit 55d9e75ffec92e922273c997026bb10613a76578</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<p>泛型用于通常我们放置类型的位置,比如函数签名或结构体,允许我们创建可以代替许多具体数据类型的结构体定义。让我们看看如何使用泛型定义函数、结构体、枚举和方法,并且在本部分的结尾我们会讨论泛型代码的性能。</p>
|
|
|
|
|
<a class="header" href="#在函数定义中使用泛型" name="在函数定义中使用泛型"><h3>在函数定义中使用泛型</h3></a>
|
|
|
|
|
<p>定义函数时可以在函数签名的参数数据类型和返回值中使用泛型。以这种方式编写的代码将更灵活并能向函数调用者提供更多功能,同时不引入重复代码。</p>
|
|
|
|
|
<p>回到<code>largest</code>函数上,列表 10-4 中展示了两个提供了相同的寻找 slice 中最大值功能的函数。第一个是从列表 10-3 中提取的寻找 slice 中<code>i32</code>最大值的函数。第二个函数寻找 slice 中<code>char</code>的最大值:</p>
|
|
|
|
|
<figure>
|
|
|
|
|
<span class="filename">Filename: src/main.rs</span>
|
|
|
|
|
<pre><code class="language-rust">fn largest_i32(list: &[i32]) -> i32 {
|
|
|
|
|
let mut largest = list[0];
|
|
|
|
|
|
|
|
|
|
for &item in list.iter() {
|
|
|
|
|
if item > largest {
|
|
|
|
|
largest = item;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
largest
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn largest_char(list: &[char]) -> char {
|
|
|
|
|
let mut largest = list[0];
|
|
|
|
|
|
|
|
|
|
for &item in list.iter() {
|
|
|
|
|
if item > largest {
|
|
|
|
|
largest = item;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
largest
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let numbers = vec![34, 50, 25, 100, 65];
|
|
|
|
|
|
|
|
|
|
let result = largest_i32(&numbers);
|
|
|
|
|
println!("The largest number is {}", result);
|
|
|
|
|
# assert_eq!(result, 100);
|
|
|
|
|
|
|
|
|
|
let chars = vec!['y', 'm', 'a', 'q'];
|
|
|
|
|
|
|
|
|
|
let result = largest_char(&chars);
|
|
|
|
|
println!("The largest char is {}", result);
|
|
|
|
|
# assert_eq!(result, 'y');
|
|
|
|
|
}
|
|
|
|
|
</code></pre>
|
|
|
|
|
<figcaption>
|
|
|
|
|
<p>Listing 10-4: Two functions that differ only in their names and the types in
|
|
|
|
|
their signatures</p>
|
|
|
|
|
</figcaption>
|
|
|
|
|
</figure>
|
|
|
|
|
<p>这里<code>largest_i32</code>和<code>largest_char</code>有着完全相同的函数体,所以能够将这两个函数变成一个来减少重复就太好了。所幸通过引入一个泛型参数就能实现。</p>
|
|
|
|
|
<p>为了参数化要定义的函数的签名中的类型,我们需要像给函数的值参数起名那样为这类型参数起一个名字。这里选择了名称<code>T</code>。任何标识符抖可以作为类型参数名,选择<code>T</code>是因为 Rust 的类型命名规范是骆驼命名法(CamelCase)。另外泛型类型参数的规范也倾向于简短,经常仅仅是一个字母。<code>T</code>作为“type”是大部分 Rust 程序员的首选。</p>
|
|
|
|
|
<p>当需要再函数体中使用一个参数时,必须再函数签名中声明这个参数以便编译器能知道函数体中这个名称的意义。同理,当在函数签名中使用一个类型参数时,必须在使用它之前就声明它。类型参数声明位于函数名称与参数列表中间的尖括号中。</p>
|
|
|
|
|
<p>我们将要定义的泛型版本的<code>largest</code>函数的签名看起来像这样:</p>
|
|
|
|
|
<pre><code class="language-rust,ignore">fn largest<T>(list: &[T]) -> T {
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>这可以理解为:函数<code>largest</code>有泛型类型<code>T</code>。它有一个参数<code>list</code>,它的类型是一个<code>T</code>值的 slice。<code>largest</code>函数将会返回一个与<code>T</code>相同类型的值。</p>
|
|
|
|
|
<p>列表 10-5 展示一个在签名中使用了泛型的统一的<code>largest</code>函数定义,并向我们展示了如何对<code>i32</code>值的 slice 或<code>char</code>值的 slice 调用<code>largest</code>函数。注意这些代码还不能编译!</p>
|
|
|
|
|
<figure>
|
|
|
|
|
<span class="filename">Filename: src/main.rs</span>
|
|
|
|
|
<pre><code class="language-rust,ignore">fn largest<T>(list: &[T]) -> T {
|
|
|
|
|
let mut largest = list[0];
|
|
|
|
|
|
|
|
|
|
for &item in list.iter() {
|
|
|
|
|
if item > largest {
|
|
|
|
|
largest = item;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
largest
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let numbers = vec![34, 50, 25, 100, 65];
|
|
|
|
|
|
|
|
|
|
let result = largest(&numbers);
|
|
|
|
|
println!("The largest number is {}", result);
|
|
|
|
|
|
|
|
|
|
let chars = vec!['y', 'm', 'a', 'q'];
|
|
|
|
|
|
|
|
|
|
let result = largest(&chars);
|
|
|
|
|
println!("The largest char is {}", result);
|
|
|
|
|
}
|
|
|
|
|
</code></pre>
|
|
|
|
|
<figcaption>
|
|
|
|
|
<p>Listing 10-5: A definition of the <code>largest</code> function that uses generic type
|
|
|
|
|
parameters but doesn't compile yet</p>
|
|
|
|
|
</figcaption>
|
|
|
|
|
</figure>
|
|
|
|
|
<p>如果现在就尝试编译这些代码,会出现如下错误:</p>
|
|
|
|
|
<pre><code>error[E0369]: binary operation `>` cannot be applied to type `T`
|
|
|
|
|
|
|
|
|
|
|
5 | if item > largest {
|
|
|
|
|
| ^^^^
|
|
|
|
|
|
|
|
|
|
|
note: an implementation of `std::cmp::PartialOrd` might be missing for `T`
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>注释中提到了<code>std::cmp::PartialOrd</code>,这是一个 <em>trait</em>。下一部分会讲到 trait,不过简单来说,这个错误表明<code>largest</code>的函数体对<code>T</code>的所有可能的类型都无法工作;因为在函数体需要比较<code>T</code>类型的值,不过它只能用于我们知道如何排序的类型。标准库中定义的<code>std::cmp::PartialOrd</code> trait 可以实现类型的排序功能。在下一部分会再次回到 trait 并讲解如何为泛型指定一个 trait,不过让我们先把这个例子放在一边并探索其他那些可以使用泛型类型参数的地方。</p>
|
|
|
|
|
<!-- Liz: this is the reason we had the topics in the order we did in the first
|
|
|
|
|
draft of this chapter; it's hard to do anything interesting with generic types
|
|
|
|
|
in functions unless you also know about traits and trait bounds. I think this
|
|
|
|
|
ordering could work out okay, though, and keep a stronger thread with the
|
|
|
|
|
`longest` function going through the whole chapter, but we do pause with a
|
|
|
|
|
not-yet-compiling example here, which I know isn't ideal either. Let us know
|
|
|
|
|
what you think. /Carol -->
|
|
|
|
|
<a class="header" href="#结构体定义中的泛型" name="结构体定义中的泛型"><h3>结构体定义中的泛型</h3></a>
|
|
|
|
|
<p>同样也可以使用<code><></code>语法来定义拥有一个或多个泛型参数类型字段的结构体。列表 10-6 展示了如何定义和使用一个可以存放任何类型的<code>x</code>和<code>y</code>坐标值的结构体<code>Point</code>:</p>
|
|
|
|
|
<figure>
|
|
|
|
|
<span class="filename">Filename: src/main.rs</span>
|
|
|
|
|
<pre><code class="language-rust">struct Point<T> {
|
|
|
|
|
x: T,
|
|
|
|
|
y: T,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let integer = Point { x: 5, y: 10 };
|
|
|
|
|
let float = Point { x: 1.0, y: 4.0 };
|
|
|
|
|
}
|
|
|
|
|
</code></pre>
|
|
|
|
|
<figcaption>
|
|
|
|
|
<p>Listing 10-6: A <code>Point</code> struct that holds <code>x</code> and <code>y</code> values of type <code>T</code></p>
|
|
|
|
|
</figcaption>
|
|
|
|
|
</figure>
|
|
|
|
|
<p>其语法类似于函数定义中的泛型应用。首先,必须在结构体名称后面的尖括号中声明泛型参数的名称。接着在结构体定义中可以指定具体数据类型的位置使用泛型类型。</p>
|
|
|
|
|
<p>注意<code>Point</code>的定义中是使用了要给泛型类型,我们想要表达的是结构体<code>Point</code>对于一些类型<code>T</code>是泛型的,而且无论这个泛型是什么,字段<code>x</code>和<code>y</code><strong>都是</strong>相同类型的。如果尝试创建一个有不同类型值的<code>Point</code>的实例,像列表 10-7 中的代码就不能编译:</p>
|
|
|
|
|
<figure>
|
|
|
|
|
<span class="filename">Filename: src/main.rs</span>
|
|
|
|
|
<pre><code class="language-rust,ignore">struct Point<T> {
|
|
|
|
|
x: T,
|
|
|
|
|
y: T,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let wont_work = Point { x: 5, y: 4.0 };
|
|
|
|
|
}
|
|
|
|
|
</code></pre>
|
|
|
|
|
<figcaption>
|
|
|
|
|
<p>Listing 10-7: The fields <code>x</code> and <code>y</code> must be the same type because both have
|
|
|
|
|
the same generic data type <code>T</code></p>
|
|
|
|
|
</figcaption>
|
|
|
|
|
</figure>
|
|
|
|
|
<p>尝试编译会得到如下错误:</p>
|
|
|
|
|
<pre><code>error[E0308]: mismatched types
|
|
|
|
|
-->
|
|
|
|
|
|
|
|
|
|
|
7 | let wont_work = Point { x: 5, y: 4.0 };
|
|
|
|
|
| ^^^ expected integral variable, found
|
|
|
|
|
floating-point variable
|
|
|
|
|
|
|
|
|
|
|
= note: expected type `{integer}`
|
|
|
|
|
= note: found type `{float}`
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>当我们将 5 赋值给<code>x</code>,编译器就知道这个<code>Point</code>实例的泛型类型<code>T</code>是一个整型。接着我们将<code>y</code>指定为 4.0,而它被定义为与<code>x</code>有着相同的类型,所以出现了类型不匹配的错误。</p>
|
|
|
|
|
<p>如果想要一个<code>x</code>和<code>y</code>可以有不同类型且仍然是泛型的<code>Point</code>结构体,我们可以使用多个泛型类型参数。在列表 10-8 中,我们修改<code>Point</code>的定义为拥有两个泛型类型<code>T</code>和<code>U</code>。其中字段<code>x</code>是<code>T</code>类型的,而字段<code>y</code>是<code>U</code>类型的:</p>
|
|
|
|
|
<figure>
|
|
|
|
|
<span class="filename">Filename: src/main.rs</span>
|
|
|
|
|
<pre><code class="language-rust">struct Point<T, U> {
|
|
|
|
|
x: T,
|
|
|
|
|
y: U,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let both_integer = Point { x: 5, y: 10 };
|
|
|
|
|
let both_float = Point { x: 1.0, y: 4.0 };
|
|
|
|
|
let integer_and_float = Point { x: 5, y: 4.0 };
|
|
|
|
|
}
|
|
|
|
|
</code></pre>
|
|
|
|
|
<figcaption>
|
|
|
|
|
<p>Listing 10-8: A <code>Point</code> generic over two types so that <code>x</code> and <code>y</code> may be
|
|
|
|
|
values of different types</p>
|
|
|
|
|
</figcaption>
|
|
|
|
|
</figure>
|
|
|
|
|
<p>现在所有这些<code>Point</code>实例都是被允许的了!你可以在定义中使用任意多的泛型类型参数,不过太多的话代码将难以阅读和理解。如果你处于一个需要很多泛型类型的位置,这可能是一个需要重新组织代码并分隔成一些更小部分的信号。</p>
|
|
|
|
|
<a class="header" href="#枚举定义中的泛型数据类型" name="枚举定义中的泛型数据类型"><h3>枚举定义中的泛型数据类型</h3></a>
|
|
|
|
|
<p>类似于结构体,枚举也可以在其成员中存放泛型数据类型。</p>
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
|
|
|
|
|
|
<a href="ch10-00-generics.html" class="mobile-nav-chapters previous">
|
|
|
|
|
<i class="fa fa-angle-left"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<a href="ch10-02-traits.html" class="mobile-nav-chapters next">
|
|
|
|
|
<i class="fa fa-angle-right"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<a href="ch10-00-generics.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
|
|
|
|
|
<i class="fa fa-angle-left"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<a href="ch10-02-traits.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
|
|
|
|
|
<i class="fa fa-angle-right"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Local fallback for Font Awesome -->
|
|
|
|
|
<script>
|
|
|
|
|
if ($(".fa").css("font-family") !== "FontAwesome") {
|
|
|
|
|
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
|
|
|
|
|
}
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Livereload script (if served using the cli tool) -->
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<script src="highlight.js"></script>
|
|
|
|
|
<script src="book.js"></script>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|