Rust 教程
- 第1节:Rust 介绍
- 第2节:Rust 安装
- 第3节:Rust Hello,world!
- 第4节:Rust Hello,Cargo!
- 第5节:Rust 栈和堆
- 第6节:Rust 测试
- 第7节:Rust 条件编译
- 第8节:Rust 文档
- 第9节:Rust 迭代器
- 第10节:Rust 并发性
- 第11节:Rust 错误处理
- 第12节:Rust 外部函数接口
- 第13节:Rust Borrow 和 AsRef
- 第14节:Rust 发布通道
- 第15节:Rust 变量绑定
- 第16节:Rust 函数
- 第17节:Rust 基本类型
- 第18节:Rust 注释
- 第19节:Rust if
- 第20节:Rust for 循环
- 第21节:Rust while 循环
- 第22节:Rust 所有权
- 第23节:Rust 引用与借用
- 第24节:Rust 生存期
- 第25节:Rust 可变性
- 第26节:Rust 结构体
- 第27节:Rust 枚举
- 第28节:Rust 匹配
- 第29节:Rust 模式
- 第30节:Rust 方法语法
- 第31节:Rust 向量
- 第32节:Rust 字符串
- 第33节:Rust 泛型
- 第34节:Rust 特征
- 第35节:Rust 降
- 第36节:Rust if let
- 第37节:Rust 特征的对象
- 第38节:Rust 闭包
- 第39节:Rust 通用函数调用语法
- 第40节:Rust 箱和模块
- 第41节:Rust “常量”和“静态”
- 第42节:Rust 属性
- 第43节:Rust type 别名
- 第44节:Rust 类型转换
- 第45节:Rust 关联类型
- 第46节:Rust 全类型
- 第47节:Rust 操作符和重载
- 第48节:Rust 'Deref'强制转换
- 第49节:Rust 宏命令
- 第50节:Rust 原始指针
- 第51节:Rust unsafe
Rust type 别名
type 别名
你可以使用 type 关键字声明另一类型的别名:
type Name = String;
然后,你可以就像使用一个真正的类型一样使用这种类型:
type Name = String;
let x: Name = "Hello".to_string();
但是请注意,这是一个别名,不完全是一个新类型。换句话说,因为 Rust 是强类型的,所以你不能比较两个不同类型:
let x: i32 = 5;
let y: i64 = 5;
if x == y {
// ...
}
这会产生这样的结果:
error: mismatched types:
expected `i32`,
found `i64`
(expected i32,
found i64) [E0308]
if x == y {
^
但是,如果我们有一个别名:
type Num = i32;
let x: i32 = 5;
let y: Num = 5;
if x == y {
// ...
}
这个编译没有错误。无论如何,Num 类型的值和 i32 类型的值是相同的。
你还可以使用泛型类型别名:
use std::result;
enum ConcreteError {
Foo,
Bar,
}
type Result<T> = result::Result<T, ConcreteError>;
这将创建一个 Result 类型的专门的版本 ,它总是有一个针对 Result< T E >
的 E 部分的 ConcreteError 。这常被用在标准库来为每一部分创建自定义错误。例如,io::Result
。