MonsterAI .Lab

Flutter • Rust • Next.js

返回首页
Rust

Rust 核心篇 (十四):Trait 特征系统——定义共享行为与孤儿规则

Waitwalker2026-08-2712 min
## 1. Trait 的定义与实现 ```rust pub trait Summary { fn summarize(&self) -> String { String::from("(Read more...)") // 默认实现 } } pub struct NewsArticle { pub headline: String, } impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}", self.headline) } } ``` ## 2. 孤儿规则 (Orphan Rule) 你只能在下列条件之一满足时为某个类型实现某个 Trait: 1. 该 Trait 定义在当前 Crate 中。 2. 该类型定义在当前 Crate 中。 这从根源上阻止了第三方库意外覆盖标准库或破坏其他库行为的可能。
#Rust#Trait#抽象设计#接口
回到文章列表 →