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

導出

コンパイラは、#[derive] 属性を介して、いくつかのトレイトに基本的な実装を提供できます。より複雑な振る舞いが必要な場合、これらのトレイトは引き続き手動で実装できます。

以下は導出可能なトレイトの一覧です。

  • 比較トレイト: Eq, PartialEq, Ord, PartialOrd.
  • Clone。コピーによって &T から T を作成します。
  • Copy。型に「ムーブセマンティクス」ではなく「コピーセマンティクス」を与えます。
  • Hash&T からハッシュを計算します。
  • Default。データ型の空のインスタンスを作成します。
  • Debug{:?} フォーマッタを使用して値をフォーマットします。
// `Centimeters`、比較可能なタプル構造体
#[derive(PartialEq, PartialOrd)]
struct Centimeters(f64);

// `Inches`、出力可能なタプル構造体
#[derive(Debug)]
struct Inches(i32);

impl Inches {
    fn to_centimeters(&self) -> Centimeters {
        let &Inches(inches) = self;

        Centimeters(inches as f64 * 2.54)
    }
}

// `Seconds`、追加の属性を持たないタプル構造体
struct Seconds(i32);

fn main() {
    let _one_second = Seconds(1);

    // エラー: `Seconds` は出力できません。`Debug` トレイトを実装していません
    //println!("One second looks like: {:?}", _one_second);
    // TODO ^ この行のコメントを解除してみましょう

    // エラー: `Seconds` は比較できません。`PartialEq` トレイトを実装していません
    //let _this_is_true = (_one_second == _one_second);
    // TODO ^ この行のコメントを解除してみましょう

    let foot = Inches(12);

    println!("One foot equals {:?}", foot);

    let meter = Centimeters(100.0);

    let cmp =
        if foot.to_centimeters() < meter {
            "smaller"
        } else {
            "bigger"
        };

    println!("One foot is {} than one meter.", cmp);
}

関連項目:

導出