進階 Trait
最後更新
本頁介紹 trait 的進階功能:關聯型別、泛型參數預設值、運算子多載、supertrait、完全限定語法與 newtype 模式。
先備知識:Trait 定義與實作、Trait bound 與 impl Trait。
關聯型別
關聯型別:trait 裡的型別佔位
關聯型別(associated type)是 trait 內宣告的「型別佔位」:
type Item;。trait 的方法可以用 Self::Item 指稱它,實作者再決定它實際是什麼。最常見的例子是
Iterator:每個迭代器都要說明「我產生什麼型別的元素」,就是 type Item(見 std::iter)。範例:
- struct Countdown(u32);
- impl Iterator for Countdown {
- type Item = u32;
- fn next(&mut self) -> Option<Self::Item> {
- if self.0 == 0 {
- None
- } else {
- self.0 -= 1;
- Some(self.0 + 1)
- }
- }
- }
- trait Storage {
- type Key;
- fn first_key(&self) -> Option<Self::Key>;
- }
- struct Shelf(Vec<&'static str>);
- impl Storage for Shelf {
- type Key = usize;
- fn first_key(&self) -> Option<usize> {
- if self.0.is_empty() { None } else { Some(0) }
- }
- }
- fn main() {
- let v: Vec<u32> = Countdown(3).collect();
- println!("{:?}", v);
- println!("{:?}", Shelf(vec!["書"]).first_key());
- println!("{:?}", Shelf(vec![]).first_key());
- }
輸出:
- [3, 2, 1]
- Some(0)
- None
關聯型別與泛型參數的差別
兩者都能讓 trait 涉及「某個型別」,差別在於一個型別能實作幾次:
泛型參數 trait T<X> | 關聯型別 type X; | |
|---|---|---|
| 同一型別可實作幾次 | 多次(每個 X 一次) | 只有一次 |
| 使用時 | 常要指定 X | 不必指定,由實作決定 |
| 標準庫例子 | From<T>、Add<Rhs> | Iterator::Item、Deref::Target |
Celsius 可以同時實作 From<f64> 與 From<i32>;但一個迭代器只會有一種 Item,所以 Iterator 用關聯型別,呼叫 next() 時就不必說明要哪一種。範例:
- struct Celsius(f64);
- impl From<f64> for Celsius {
- fn from(v: f64) -> Self {
- Celsius(v)
- }
- }
- impl From<i32> for Celsius {
- fn from(v: i32) -> Self {
- Celsius(v as f64)
- }
- }
- fn main() {
- let a = Celsius::from(36.5);
- let b: Celsius = 20.into();
- println!("{}°C {}°C", a.0, b.0);
- }
輸出:
- 36.5°C 20°C
運算子多載
實作 Add,讓 + 可以用在自己的型別
Rust 不能發明新的運算子,但可以為自己的型別實作 std::ops 裡對應的 trait,讓既有的運算子能用:
+ 對應 Add、- 對應 Sub、* 對應 Mul、-x 對應 Neg、a[i] 對應 Index。比較運算子 ==、< 則對應 std::cmp 的 PartialEq、PartialOrd。Add 有一個關聯型別 Output,表示相加的結果是什麼型別。範例:
- use std::ops::{Add, Neg};
- #[derive(Debug, Clone, Copy, PartialEq)]
- struct Vec2 {
- x: i32,
- y: i32,
- }
- impl Add for Vec2 {
- type Output = Vec2;
- fn add(self, other: Vec2) -> Vec2 {
- Vec2 { x: self.x + other.x, y: self.y + other.y }
- }
- }
- impl Neg for Vec2 {
- type Output = Vec2;
- fn neg(self) -> Vec2 {
- Vec2 { x: -self.x, y: -self.y }
- }
- }
- fn main() {
- let a = Vec2 { x: 1, y: 2 };
- let b = Vec2 { x: 10, y: 20 };
- println!("{:?}", a + b);
- println!("{:?}", -a);
- println!("{}", a + b == Vec2 { x: 11, y: 22 });
- }
輸出:
- Vec2 { x: 11, y: 22 }
- Vec2 { x: -1, y: -2 }
- true
泛型參數預設值:Rhs = Self
Add 的定義是 trait Add<Rhs = Self>:型別參數 Rhs(右邊運算元的型別)有預設值 Self。所以 impl Add for Vec2 等於 impl Add<Vec2> for Vec2。需要「不同型別相加」時,明確寫出 Rhs,例如向量乘以純量、公尺加公分。自己定義 trait 時也能用這個語法:
trait Scale<Factor = f64>,大多數使用者不必寫型別參數,少數需要時再指定。範例:
- use std::ops::{Add, Mul};
- #[derive(Debug, Clone, Copy)]
- struct Vec2 {
- x: f64,
- y: f64,
- }
- impl Mul<f64> for Vec2 {
- type Output = Vec2;
- fn mul(self, k: f64) -> Vec2 {
- Vec2 { x: self.x * k, y: self.y * k }
- }
- }
- #[derive(Debug)]
- struct Meters(f64);
- #[derive(Debug)]
- struct Centimeters(f64);
- impl Add<Centimeters> for Meters {
- type Output = Meters;
- fn add(self, cm: Centimeters) -> Meters {
- Meters(self.0 + cm.0 / 100.0)
- }
- }
- fn main() {
- let v = Vec2 { x: 1.5, y: -2.0 };
- println!("{:?}", v * 2.0);
- println!("{:?}", Meters(1.0) + Centimeters(25.0));
- }
輸出:
- Vec2 { x: 3.0, y: -4.0 }
- Meters(1.25)
supertrait
trait A: B:要實作 A 必須先實作 B
有時一個 trait 需要用到另一個 trait 的功能。寫成
trait Outline: Display,表示「要實作 Outline,型別必須先實作 Display」。Display 稱為 Outline 的 supertrait(父特徵),Outline 的預設方法裡就能使用 {} 印出 self。範例:
- use std::fmt;
- trait Outline: fmt::Display {
- fn outline(&self) -> String {
- let text = self.to_string();
- let line = "*".repeat(text.chars().count() + 4);
- format!("{}\n* {} *\n{}", line, text, line)
- }
- }
- struct Tag(&'static str);
- impl fmt::Display for Tag {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "#{}", self.0)
- }
- }
- impl Outline for Tag {}
- fn main() {
- println!("{}", Tag("rust").outline());
- }
輸出:
- *********
- * #rust *
- *********
注意:若
Tag 沒有實作 Display 就寫 impl Outline for Tag {},會出現 E0277 錯誤,指出 Tag 沒有實作 Display。完全限定語法
同名方法:指定要呼叫哪一個
一個型別可能從不同 trait 得到同名的方法,自己也可能有同名的方法。直接寫
x.name() 時,Rust 優先呼叫型別自己的方法;要呼叫 trait 的版本,寫成 Trait::method(&x)。範例:
- trait Pilot {
- fn title(&self) -> String;
- }
- trait Wizard {
- fn title(&self) -> String;
- }
- struct Human;
- impl Pilot for Human {
- fn title(&self) -> String { String::from("機長") }
- }
- impl Wizard for Human {
- fn title(&self) -> String { String::from("大法師") }
- }
- impl Human {
- fn title(&self) -> String { String::from("普通人") }
- }
- fn main() {
- let h = Human;
- println!("{}", h.title());
- println!("{}", Pilot::title(&h));
- println!("{}", Wizard::title(&h));
- }
輸出:
- 普通人
- 機長
- 大法師
<Type as Trait>::function:沒有 self 的關聯函式
沒有
self 參數的關聯函式(例如 fn kind() -> String),Trait::kind() 這種寫法無法判斷要用哪個型別的實作。這段無法編譯:範例:
- trait Animal {
- fn kind() -> String;
- }
- struct Dog;
- impl Animal for Dog {
- fn kind() -> String { String::from("狗") }
- }
- fn main() {
- println!("{}", Animal::kind());
- }
輸出:
- error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
- --> main.rs:12:20
- |
- 2 | fn kind() -> String;
- | -------------------- `Animal::kind` defined here
- ...
- 12 | println!("{}", Animal::kind());
- | ^^^^^^^^^^^^^^ cannot call associated function of trait
這時要用完全限定語法(fully qualified syntax)
<Type as Trait>::function(),同時寫出型別與 trait。型別自己也有同名函式時,Dog::kind() 呼叫的是型別自己的版本。範例:
- trait Animal {
- fn kind() -> String;
- }
- struct Dog;
- impl Dog {
- fn kind() -> String { String::from("小狗(Dog 自己的函式)") }
- }
- impl Animal for Dog {
- fn kind() -> String { String::from("犬科(Animal 的實作)") }
- }
- fn main() {
- println!("{}", Dog::kind());
- println!("{}", <Dog as Animal>::kind());
- }
輸出:
- 小狗(Dog 自己的函式)
- 犬科(Animal 的實作)
newtype 模式
newtype 是「只有一個欄位的元組結構體」,例如
struct Meters(f64);。它在執行期沒有成本(大小與內部的值相同),卻是一個全新的型別。用 newtype 繞過孤兒規則
孤兒規則不允許為外部型別實作外部 trait,例如為
Vec<String> 實作 Display。用 newtype 包一層,型別就變成自己的,可以自由實作。缺點是 Vec 的方法不再能直接呼叫,要透過 .0 存取。範例:
- use std::fmt;
- struct Tags(Vec<String>);
- impl fmt::Display for Tags {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "[{}]", self.0.join(", "))
- }
- }
- fn main() {
- let mut t = Tags(vec![String::from("rust"), String::from("trait")]);
- t.0.push(String::from("newtype"));
- println!("{}({} 個)", t, t.0.len());
- }
輸出:
- [rust, trait, newtype](3 個)
用 newtype 區分意義不同的值
公尺與秒都是
f64,混用不會被編譯器發現。各自包成 newtype 後,參數順序寫反就會編譯錯誤,讓型別系統幫你檢查單位。範例:
- use std::mem::size_of;
- #[derive(Debug, Clone, Copy)]
- struct Meters(f64);
- #[derive(Debug, Clone, Copy)]
- struct Seconds(f64);
- fn speed(d: Meters, t: Seconds) -> f64 {
- d.0 / t.0
- }
- fn main() {
- let d = Meters(100.0);
- let t = Seconds(9.58);
- println!("{:.2} m/s", speed(d, t));
- println!("Meters 大小 {} bytes,f64 大小 {} bytes", size_of::<Meters>(), size_of::<f64>());
- }
輸出:
- 10.44 m/s
- Meters 大小 8 bytes,f64 大小 8 bytes
若寫成
speed(t, d),會得到 error[E0308]: arguments to this function are incorrect。重點整理
- 關聯型別
type Item;讓實作者決定 trait 用到的型別,每個型別只能實作一次 - 實作
std::ops的Add、Mul、Neg等 trait 即可多載運算子;Rhs = Self是泛型參數預設值 trait A: B宣告 supertrait,實作A前必須先實作B- 同名方法用
Trait::method(&x),沒有self的函式用<Type as Trait>::f() - newtype 繞過孤兒規則、區分意義不同的值,且沒有執行期成本