在 Rust 类型系统中,结构体(Struct)和枚举体(Enum)都属于 代数数据类型(ADT, Algebraic Data Type)

ADT 指的是指的是具备代数能力的数据类型,即数据类型可以进行代数运算并满足一定的运算规则。比如一个结构体 中的所有成员是可以复制的,那么这个结构体就可以通过派生属性 #[derive] 实现 Copy 。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#[derive(Debug, Copy, Clone)]
struct Book<'a> {
    name: &'a str,
    isbn: i32,
    version: i32,
}

fn main() {
    let book = Book {
        name: "Rust 编程之道",
        isbn: 20181212,
        version: 1,
    };

    let book2 = Book { version: 2, ..book }; // 结构体更新语法
    println!("{:?}", book);
    println!("{:?}", book2);
}

如果结构体中有字段为移动语义,则无法直接通过继承实现 Copy 。Rust 中的结构体是代数类型中的积类型。

下面利用结构体实现带颜色的字符输出。

 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
struct ColoredString {
    input: String,
    fgcolor: String,
    bgcolor: String,
}

trait Colorize {
    const FG_RED: &'static str = "31"; // 关联常量,名字必须大写
    const BG_YELLOW: &'static str = "43";
    fn red(self) -> ColoredString;
    fn on_yellow(self) -> ColoredString;
}

// 实现默认方法
impl Default for ColoredString {
    fn default() -> Self {
        ColoredString {
            input: String::default(),
            fgcolor: String::default(),
            bgcolor: String::default(),
        }
    }
}

// 为 ColoredString 实现 Colorize trait

impl<'a> Colorize for ColoredString {
    fn red(self) -> ColoredString {
        ColoredString {
            fgcolor: String::from(ColoredString::FG_RED),
            ..self
        }
    }

    fn on_yellow(self) -> ColoredString {
        ColoredString {
            bgcolor: String::from(ColoredString::BG_YELLOW),
            ..self
        }
    }
}

impl<'a> Colorize for &'a str {
    fn red(self) -> ColoredString {
        ColoredString {
            fgcolor: String::from(ColoredString::FG_RED),
            input: String::from(self),
            ..ColoredString::default()
        }
    }

    fn on_yellow(self) -> ColoredString {
        ColoredString {
            bgcolor: String::from(ColoredString::BG_YELLOW),
            input: String::from(self),
            ..ColoredString::default()
        }
    }
}

impl ColoredString {
    fn compute_style(&self) -> String {
        let mut res = String::from("\x1B[");
        let mut has_wrote = false;
        if !self.bgcolor.is_empty() {
            res.push_str(&self.bgcolor);
            has_wrote = true;
        }
        if !self.fgcolor.is_empty() {
            if has_wrote {
                res.push_str(";");
            }
            res.push_str(&self.fgcolor);
        }
        res.push('m');
        res
    }
}

use std::fmt;

impl fmt::Display for ColoredString {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&self.compute_style())?;
        f.write_str(&self.input)?;
        f.write_str("\x1B[0m")?;
        Ok(())
    }
}

fn main() {
    let hi = "Hello".red().on_yellow();
    println!("{}", hi);
}