这个章节会详细介绍特性的关联类型(Associated Type)、操作符多载(Operator Overloading)的实作方式、调用名称相同但属于不同特性的方法或关联函数、替外部的类型实作新的特性。
特性的关联类型
我们在先前的章节使用 Iterator 特性实作迭代器的时候,就有用到特性的关联类型,但是并没有针对它进行说明。特性的关联类型就是定义出一个名称来代表一个类型,且这个名称可以被使用在特性内所定义的关联函数或是方法。也就是说,当我们使用 impl 关键字来实作这个特性时,可以决定特性的关联类型名称所代表的实际类型,能使同一个特性在不同的实作下,其关联函数和方法能够拥有不同的签名和回传值类型。
举例来说:
trait MyTrait {
type SomeType;
fn do_something(&mut self, obj: Self::SomeType);
}
struct MyStruct1 {}
impl MyTrait for MyStruct1 {
type SomeType = i32;
fn do_something(&mut self, obj: Self::SomeType) {
println!("{obj}");
}
}
struct MyStruct2 {}
impl MyTrait for MyStruct2 {
type SomeType = String;
fn do_something(&mut self, obj: Self::SomeType) {
println!("{obj}");
}
}
fn main() {}
以上程序,MyTrait 特性有一个关联类型名称 SomeType,且 do_something 方法的 obj 参数的类型为 SomeType。程序第 9 行到第 15 行,替 MyStruct1 结构体实作 MyTrait 特性,将关联类型名称 SomeType 指定为 i32 类型,因此 do_something 方法的 obj 参数的类型为 i32。程序第 19 行到第 25 行,替 MyStruct2 结构体实作 MyTrait 特性,将关联类型名称 SomeType 指定为 String 类型,因此 do_something 方法的 obj 参数的类型为 String。
当然,我们之前学到的泛型也可以完成类似的功能。举例来说:
trait MyTrait<SomeType> {
fn do_something(&mut self, obj: SomeType);
}
struct MyStruct1 {}
impl MyTrait<i32> for MyStruct1 {
fn do_something(&mut self, obj: i32) {
println!("{obj}");
}
}
struct MyStruct2 {}
impl MyTrait<String> for MyStruct2 {
fn do_something(&mut self, obj: String) {
println!("{obj}");
}
}
fn main() {}
使用泛型还有一个好处,就是我们可以替相同的类型实作很多种 MyTrait 特性。举例来说:
trait MyTrait<SomeType> {
fn do_something(&mut self, obj: SomeType);
}
struct MyStruct1 {}
impl MyTrait<i32> for MyStruct1 {
fn do_something(&mut self, obj: i32) {
println!("{obj}");
}
}
impl MyTrait<String> for MyStruct1 {
fn do_something(&mut self, obj: String) {
println!("{obj}");
}
}
fn main() {}
如果要把拥有关联类型的特性作为类型来使用的话,无法直接使用特性名称来代替类型名称。举例来说:
trait MyTrait {
type SomeType;
fn do_something(&mut self, obj: Self::SomeType);
}
struct MyStruct {}
impl MyTrait for MyStruct {
type SomeType = i32;
fn do_something(&mut self, obj: Self::SomeType) {
println!("{}", obj);
}
}
struct HoldMyTrait {
data: Box<dyn MyTrait>
}
fn main() {}
以上程序第 18 行会编译失败,因为 MyTrait 特性有使用到关联类型,我们必须要替 MyTrait 特性的关联类型对应的类型明确定义出来,才可以将 MyTrait 特性作为类型使用。这部份其实就类似泛型,写法如下:
trait MyTrait {
type SomeType;
fn do_something(&mut self, obj: Self::SomeType);
}
struct MyStruct {}
impl MyTrait for MyStruct {
type SomeType = i32;
fn do_something(&mut self, obj: Self::SomeType) {
println!("{obj}");
}
}
struct HoldMyTrait {
data: Box<dyn MyTrait<SomeType = i32>>,
}
fn main() {}
利用 = 符号,可以在 <> 泛型语法中指定关联类型名称所对应的类型。
那如果特性同时有关联类型和泛型的话该怎么办呢?举例来说:
trait MyTrait<T> {
type SomeType;
fn do_something(&mut self, obj: Self::SomeType);
}
struct MyStruct {}
impl<T> MyTrait<T> for MyStruct {
type SomeType = i32;
fn do_something(&mut self, obj: Self::SomeType) {
println!("{obj}");
}
}
struct HoldMyTrait {
data: Box<dyn MyTrait<i32, SomeType=MyStruct>>
}
我们必须将 <> 泛型语法中的关联类型对应放在泛型类型参数后面。
操作符多载
我们无法在 Rust 编程语言中创建出新的操作符,也无法多载(overload)任意操作符。我们只能透过实作标准函数库中的 std::ops 模块所提供的相关特性,来完成操作符的多载。例如我们想要让我们实作的结构实体能支持 + 运算,我们就必须替该结构体实作 Add 特性。
我们可以观察一下 Add 特性的定义:
trait Add<RHS=Self> {
/// The resulting type after applying the `+` operator.
#[stable(feature = "rust1", since = "1.0.0")]
type Output;
/// Performs the `+` operation.
#[stable(feature = "rust1", since = "1.0.0")]
fn add(self, rhs: RHS) -> Self::Output;
}
Add 特性有一个泛型类型参数 RHS,这边有个我们之前没学过的语法,那就是利用等号 = 来设置泛型类型参数的「默认值」。举例来说:
trait MyTrait<T = i32> {
fn do_something(&mut self, obj: T);
}
struct MyStruct1 {}
impl MyTrait for MyStruct1 {
fn do_something(&mut self, obj: i32) {
println!("{obj}");
}
}
impl MyTrait<String> for MyStruct1 {
fn do_something(&mut self, obj: String) {
println!("{obj}");
}
}
fn main() {}
以上程序第 7 行,MyTrait 其实就是 MyTrait<i32>。
因此,如果不特别指定 Add 特性的泛型类型参数 RHS 究竟是哪个类型的话,预设就会是实作这个特性的类型自己。举例来说:
use std::ops::Add;
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point { x: self.x + other.x, y: self.y + other.y }
}
}
impl Add<(i32, i32)> for Point {
type Output = Point;
fn add(self, other: (i32, i32)) -> Point {
Point { x: self.x + other.0, y: self.y + other.1 }
}
}
fn main() {
println!("{:?}", Point { x: 1, y: 0 } + Point { x: 2, y: 3 });
println!("{:?}", Point { x: 1, y: 0 } + (2, 3));
}
以上程序,第 9 行的 Add 其实就是 Add<Point>。我们替 Point 结构体实作了 Add<Point> 和 Add<(i32, i32)>,因此 Point 结构实体可以和 Point 结构实体或是 (i32, i32) 元组进行 + 运算。程序运行结果如下:
Point { x: 3, y: 3 }
调用名称相同但属于不同特性的方法
先看看以下代码吧!
trait Pilot {
fn fly(&self);
}
trait Wizard {
fn fly(&self);
}
struct Human {}
impl Pilot for Human {
fn fly(&self) {
println!("This is your captain speaking.");
}
}
impl Wizard for Human {
fn fly(&self) {
println!("Up!");
}
}
fn main() {
let person = Human {};
person.fly();
}
这个程序第 26 行会编译错误,因为 Human 结构体实作的 Pilot 特性和 Wizard 特性都有 fly 方法,编译器不知道到底要运行哪个 fly 方法。不过,如果 Human 结构体本身也有实作 fly 方法的话,程序第 26 行是可以通过编译的,且只会调用到 Human 结构体本身实作的 fly 方法。如下:
trait Pilot {
fn fly(&self);
}
trait Wizard {
fn fly(&self);
}
struct Human {}
impl Pilot for Human {
fn fly(&self) {
println!("This is your captain speaking.");
}
}
impl Wizard for Human {
fn fly(&self) {
println!("Up!");
}
}
impl Human {
fn fly(&self) {
println!("*waving arms furiously*");
}
}
fn main() {
let person = Human {};
person.fly();
}
我们虽然替 Human 结构体本身实作了 fly 方法,但如果我们还是想要使用到 Pilot 特性和 Wizard 特性的 fly 方法时该怎么办呢?其实很简单,只要换个语法来调用方法就好,程序如下:
trait Pilot {
fn fly(&self);
}
trait Wizard {
fn fly(&self);
}
struct Human {}
impl Pilot for Human {
fn fly(&self) {
println!("This is your captain speaking.");
}
}
impl Wizard for Human {
fn fly(&self) {
println!("Up!");
}
}
impl Human {
fn fly(&self) {
println!("*waving arms furiously*");
}
}
fn main() {
let person = Human {};
Pilot::fly(&person);
Wizard::fly(&person);
person.fly();
}
调用名称相同但属于不同特性的关联函数
刚才我们介绍的是调用名称相同但属于不同特性的「方法」,现在来看看如果是要调用「关联函数」的话,要怎么做吧!
先看看以下代码:
trait Pilot {
fn fly();
}
trait Wizard {
fn fly();
}
struct Human {}
impl Pilot for Human {
fn fly() {
println!("This is your captain speaking.");
}
}
impl Wizard for Human {
fn fly() {
println!("Up!");
}
}
fn main() {
Human::fly();
}
这个程序第 24 行会编译错误,因为 Human 结构体实作的 Pilot 特性和 Wizard 特性都有 fly 关联函数,编译器不知道到底要运行哪个 fly 关联函数。不过,如果 Human 结构体本身也有实作 fly 关联函数的话,程序第 24 行是可以通过编译的,且只会调用到 Human 结构体本身实作的 fly 关联函数。如下:
trait Pilot {
fn fly();
}
trait Wizard {
fn fly();
}
struct Human {}
impl Pilot for Human {
fn fly() {
println!("This is your captain speaking.");
}
}
impl Wizard for Human {
fn fly() {
println!("Up!");
}
}
impl Human {
fn fly() {
println!("*waving arms furiously*");
}
}
fn main() {
Human::fly();
}
我们虽然替 Human 结构体本身实作了 fly 关联函数,但如果我们还是想要使用到 Pilot 特性和 Wizard 特性的 fly 关联函数时该怎么办呢?关联函数并不像方法一样能够接受 self 参数,有办法用类似刚才介绍调用方法的方式来调用关联函数吗?我们尝试撰写出以下程序:
trait Pilot {
fn fly();
}
trait Wizard {
fn fly();
}
struct Human {}
impl Pilot for Human {
fn fly() {
println!("This is your captain speaking.");
}
}
impl Wizard for Human {
fn fly() {
println!("Up!");
}
}
impl Human {
fn fly() {
println!("*waving arms furiously*");
}
}
fn main() {
Pilot::fly();
Wizard::fly();
Human::fly();
}
程序第 30 行和第 31 行会编译错误,因为编译器不知道特性的抽象关联函数究竟是如何实作的,我们必须要使用 <Type as Trait>::function 这样的语法来指定要调用类型的哪个特性所实作的关联函数。程序需要改写如下:
trait Pilot {
fn fly();
}
trait Wizard {
fn fly();
}
struct Human {}
impl Pilot for Human {
fn fly() {
println!("This is your captain speaking.");
}
}
impl Wizard for Human {
fn fly() {
println!("Up!");
}
}
impl Human {
fn fly() {
println!("*waving arms furiously*");
}
}
fn main() {
<Human as Pilot>::fly();
<Human as Wizard>::fly();
Human::fly();
}
替外部的类型实作新的特性
替类型实作特性,该类型和特性两者中必须要有一个是定义在目前的 crate,否则无法编译。
举例来说:
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error;
impl Display for Vec<i32> {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
Ok(())
}
}
fn main() {}
以上程序,尝试替 Rust 编程语言标准函数库中的 Vec<i32> 结构体实作同样位于标准函数库中的 Display 特性,由于 Vec 结构体和 Display 特性没有一个是定义在目前的 crate 下,因此程序会编译失败。想要让这个程序能够编译成功,我们需要在目前的 crate 创建一个新的结构体来保存 Vec 结构实体,有点类似替一个既有的类型创建出一个新的类型的概念,且为了简化结构体,通常会使用元组结构体来完成这件事。程序如下:
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error;
struct MyVec<T>(Vec<T>);
impl Display for MyVec<i32> {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
Ok(())
}
}
fn main() {}
创建出我们自己的新类型除了可以让我们能够替它实作更多来自于其它 crate 的特性之外,还可以重新替原本的类型定义新的公开的关联函数或是方法。我们也可以将原本拥有泛型参数的类型包装成没有泛型参数的类型,使它更容易被使用。
结论
这个章节我们学会了特性的关联类型用法,也知道如何实作标准函数库中的 std::ops 模块提供的相关特性来多载操作符,能够让我们实作出来的结构体或是枚举更方便使用。我们甚至还考虑到当遇到特性的关联函数和方法名称有冲突时的情况,能够使用不同的语法来将它们区分出来调用。也学会了利用创建一个新结构体来包裹一个不在目前 crate 中的类型的方式,来实作也不在目前 crate 中的特性。
在下一章节,我们将会学习高级的类型用法。
下一章:高级的类型用法。
