rust-traits - 課題

概要

Rustのトレイトシステムを理解し、ポリモーフィズムとジェネリックプログラミングを実践する課題です。

マンダトリーパート

必須要件

  • カスタムトレイトの定義と実装
- 複数のメソッドを持つトレイト - デフォルト実装 - 関連型

  • ジェネリック関数とトレイト境界
- 複数のトレイト境界 - where句の使用

  • 標準トレイトの実装
- Display, Debug - From, Into - Iterator

インターフェース

/// 基本的なドキュメントトレイト
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 のみ許可
  • マクロの過度な使用は禁止