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)

Компілятор здатний надавати базові реалізації для деяких трейтів за допомогою атрибута #[derive] атрибут. Ці трейт можуть і далі бути реалізовані вручну, якщо потрібна складніша поведінка.

Нижче наведено список трейтів, для яких можливе виведення:

  • Трейтів для порівняння: Eq, PartialEq, Ord, PartialOrd.
  • 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);
}

Дивіться також:

derive