Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

トレイト

もちろん、trait もジェネリックにできます。ここでは、自身と入力を drop するジェネリックメソッドとして Drop trait を再実装するものを定義します。

// コピーできない型。
struct Empty;
struct Null;

// `T` に対してジェネリックなトレイト。
trait DoubleDrop<T> {
    // 呼び出し元の型にメソッドを定義する。このメソッドは
    // 追加の単一パラメーター `T` を受け取り、それに対して何もしない。
    fn double_drop(self, _: T);
}

// 任意のジェネリックパラメーター `T` と
// 呼び出し元 `U` に対して `DoubleDrop<T>` を実装する。
impl<T, U> DoubleDrop<T> for U {
    // このメソッドは渡された両方の引数の所有権を取得し、
    // 両方を解放する。
    fn double_drop(self, _: T) {}
}

fn main() {
    let empty = Empty;
    let null  = Null;

    // `empty` と `null` を解放する。
    empty.double_drop(null);

    //empty;
    //null;
    // ^ TODO: これらの行をアンコメントしてみましょう。
}

関連項目:

Dropstruct、および trait