Rust•トレイト
Rust のトレイト:共有振る舞いとポリモーフィズム
Rust は従来の継承の代わりにトレイトを用い、型をまたいだ共有機能の契約を定義します。
構文
trait Describable {
fn describe(&self) -> String;
}
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| trait | Keyword | 共有される振る舞いの契約を定義します。 |
そのまま実行できるコード例
Compilra で実行可能Rust をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
trait HealthChecker {
fn check_health(&self) -> String;
}
struct DatabaseNode {
name: String,
active_conns: u32,
}
impl HealthChecker for DatabaseNode {
fn check_health(&self) -> String {
format!("{}: OK ({} active connections)", self.name, self.active_conns)
}
}
// Function accepting generic type bounded by trait
fn run_diagnostic<T: HealthChecker>(item: &T) {
println!("[DIAGNOSTIC] {}", item.check_health());
}
fn main() {
let db = DatabaseNode {
name: String::from("PostgresCluster"),
active_conns: 42,
};
run_diagnostic(&db);
}期待される出力:
[DIAGNOSTIC] PostgresCluster: OK (42 active connections)
動作のしくみ: ステップ解説
- 1〜3行目: HealthChecker トレイトを定義します。
- 10〜14行目: DatabaseNode に対してトレイトを実装します。
- 17〜19行目: ジェネリック関数が静的単相化のためトレイト境界 <T: HealthChecker> を使用します。
重要ポイント
- Rust のトレイトは他言語のインタフェースや抽象基底クラスに相当します。
- トレイト境界はコンパイル時にゼロコストの単相化コードを生成します。
- 動的ディスパッチはトレイトオブジェクト &dyn Trait で実現します。
よくある間違い: 基底構造体からフィールドを継承しようとすること
Rust に構造体継承はありません。コンポジション(構造体の中に別構造体を持たせる)とトレイトを使ってください。
❌ 誤り
struct Child : Parent { ... } // Syntax Error!✅ 正しい例
struct Child { parent_data: Parent, extra: u32 }