rust-traits - 課題
概要
Rustのトレイトシステムを理解し、ポリモーフィズムとジェネリックプログラミングを実践する課題です。
マンダトリーパート
必須要件
- カスタムトレイトの定義と実装
- ジェネリック関数とトレイト境界
- 標準トレイトの実装
インターフェース
/// 基本的なドキュメントトレイト
pub trait Document {
fn title(&self) -> &str;
fn content(&self) -> &str;
/// デフォルト実装
fn summary(&self) -> String {
format!("{}: {:.50}...", self.title(), self.content())
}
}
/// 関連型を持つトレイト
pub trait Parser {
type Output;
type Error;
fn parse(&self, input: &str) -> Result<Self::Output, Self::Error>;
}
/// ジェネリックな処理
pub fn process<T: Document + Clone>(doc: T) -> String {
// 実装
}
/// where句を使用
pub fn merge<T, U>(a: T, b: U) -> String
where
T: Document,
U: Document,
{
// 実装
}
/// 標準トレイト実装が必要な構造体
pub struct Article {
pub title: String,
pub author: String,
pub body: String,
}
// Display, Debug, Clone, From<&str> を実装
使用例
let article = Article::new("Title", "Author", "Body content");
println!("{}", article); // Display
println!("{:?}", article); // Debug
let doc: Box<dyn Document> = Box::new(article);
println!("{}", doc.summary());
ボーナスパート
ボーナス1: トレイトオブジェクト
- 動的ディスパッチの実装
dyn Traitの活用
ボーナス2: マーカートレイト
- カスタムマーカートレイトの作成
- 型制約としての使用
ボーナス3: 高度なトレイト
- Deref, DerefMut
- Index, IndexMut
src/traits.rs- カスタムトレイトsrc/impls.rs- 実装src/generics.rs- ジェネリック関数Cargo.toml- 依存関係- 外部クレートは
thiserrorのみ許可 - マクロの過度な使用は禁止