01-派生
派生 — Rust By Example
译文 · 基于 Rust By Example
原文链接: https://doc.rust-lang.org/stable/rust-by-example/trait/derive.html
派生
通过 #[derive] 属性,编译器能够提供某些 trait 的基本实现。如果需要更复杂的行为,这些 trait 也可以手动实现。
下面是可以自动派生的 trait:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| // `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` trait
//println!("One second looks like: {:?}", _one_second);
// 试一试 ^ 取消此行注释
// 报错:`Seconds`不能比较;它没有实现 `PartialEq` trait
//let _this_is_true = (_one_second == _one_second);
// 试一试 ^ 取消此行注释
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