派生

编译器可以通过 #[derive] 属性为某些 trait 提供基本的实现。如果需要更复杂的行为,这些 trait 仍然可以手动实现。

以下是可派生 trait 的列表

  • 比较 trait:EqPartialEqOrdPartialOrd
  • Clone,通过复制从 &T 创建 T
  • Copy,为类型赋予“复制语义”而不是“移动语义”。
  • Hash,从 &T 计算哈希值。
  • Default,创建数据类型的空实例。
  • Debug,使用 {:?} 格式化器格式化值。
// `Centimeters`, a tuple struct that can be compared
#[derive(PartialEq, PartialOrd)]
struct Centimeters(f64);

// `Inches`, a tuple struct that can be printed
#[derive(Debug)]
struct Inches(i32);

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

        Centimeters(inches as f64 * 2.54)
    }
}

// `Seconds`, a tuple struct with no additional attributes
struct Seconds(i32);

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

    // Error: `Seconds` can't be printed; it doesn't implement the `Debug` trait
    //println!("One second looks like: {:?}", _one_second);
    // TODO ^ Try uncommenting this line

    // Error: `Seconds` can't be compared; it doesn't implement the `PartialEq` trait
    //let _this_is_true = (_one_second == _one_second);
    // TODO ^ Try uncommenting this line

    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);
}

另请参阅

派生