當然沒問題!讓我再帶你進入 Rust 王國,展開更神奇、更複雜的泛型進階冒險,用逗趣故事幫你搞懂!
故事標題:
「Rust 王國的變形勇士與神奇界限 — 泛型的進階魔法書」
在 Rust 王國裡,隨著冒險越來越兇險,國王決定要招募一批「變形勇士」。這些勇士不但要會揮劍、騎馬,還能根據不同情境變形,變出不同的武器和技能。
但國王很挑剔,他最大的要求是:這些勇士必須能掌握「對自己能力的自我限定」,也就是說,勇士的「武器型態」必須符合特殊條件,否則他不能參加戰鬥。
變形勇士泛型 T 與他的秘密武器型態 Weapon
Rust 王國的法師跟勇士協議:
trait Sword {
fn swing(&self);
}
trait Rider {
fn ride(&self);
}
trait Weapon {
fn damage(&self) -> u32;
}
// 我們有一個變形勇士 T,他會帶一個武器 W
struct Shapeshifter<T, W>
where
T: Sword + Rider, // 勇士必須會揮劍和騎馬
W: Weapon, // 武器也必須符合 Weapon 特徵
{
hero: T,
weapon: W,
}
impl<T, W> Shapeshifter<T, W>
where
T: Sword + Rider,
W: Weapon,
{
fn fight(&self) {
self.hero.swing();
self.hero.ride();
println!("用武器造成了 {} 點傷害!", self.weapon.damage());
}
}
這邊的重點是:
Shapeshifter 是泛型結構,有兩個類型參數 T 和 W,代表勇士和武器。
where 限制「勇士要有揮劍和騎馬技能」;
- 且「武器必須是 Weapon」能夠傷敵。
逗趣角色登場!
struct Knight;
impl Sword for Knight {
fn swing(&self) {
println!("騎士揮劍斬擊!");
}
}
impl Rider for Knight {
fn ride(&self) {
println!("騎士策馬奔騰!");
}
}
struct DragonSword;
impl Weapon for DragonSword {
fn damage(&self) -> u32 {
100
}
}
struct PeacefulWizard;
impl Sword for PeacefulWizard {
fn swing(&self) {
println!("和平巫師優雅地揮動魔杖...");
}
}
// 巫師不會騎馬,不符合 Rider
戲劇演出:
fn main() {
let knight = Knight;
let sword = DragonSword;
let hero = Shapeshifter { hero: knight, weapon: sword };
hero.fight();
// 下面這行會編譯錯誤,因為 PeacefulWizard 沒有 Rider
/*
let wizard = PeacefulWizard;
let hero2 = Shapeshifter { hero: wizard, weapon: sword };
hero2.fight();
*/
}
進階魔法:關聯型態(Associated Types)
Rust 國王又學會了一招更厲害的魔法,他決定讓勇士自己定義他們會用什麼武器,武器的型態綁定在勇士身上!這樣泛型更智慧!
巫師進化版:
trait Warrior {
type WeaponType: Weapon; // 關聯型態,勇士會定義自己的武器類型
fn swing(&self);
fn ride(&self);
fn weapon(&self) -> Self::WeaponType;
}
struct Shapeshifter2<T>
where
T: Warrior,
{
hero: T,
}
impl<T> Shapeshifter2<T>
where
T: Warrior,
{
fn fight(&self) {
self.hero.swing();
self.hero.ride();
let w = self.hero.weapon();
println!("武器造成了 {} 點傷害!", w.damage());
}
}
角色調整:
struct Knight2;
impl Warrior for Knight2 {
type WeaponType = DragonSword;
fn swing(&self) {
println!("騎士2揮劍!");
}
fn ride(&self) {
println!("騎士2騎馬!");
}
fn weapon(&self) -> Self::WeaponType {
DragonSword
}
}
結尾小笑話
有位勇士問國王:「國王大人,我為什麼要定關聯型態?多麻煩...」
國王答:「讓你的武器跟你本人才是真正的一體兩面啊,這樣才能打怪不分心,還能省下選武器的時間!」
總結:
- 泛型的多重限制很像給勇士設定多重考驗。
where 讓限制條件更清晰可讀。
- 兩個泛型參數,讓你能表達「勇士和武器」互相搭配的關係。
- 進階的關聯型態,則是讓泛型變得更智慧、更貼近現實世界的「一對一配件」。
希望這故事讓你秒懂泛型進階用法!再遇到複雜跟你不熟的泛型,就想像是在管理什麼神奇的勇士和神器吧~
隨時歡迎再來聽我說冒險故事! 🏰⚔️🧙♂️