Rust 中的 RAII 模式

一个送信的逻辑:

 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
#[derive(Clone)]
pub struct Letter {
    text: String,
}

pub struct Envelope {
    letter: Option<Letter>,
}

pub struct PickupLorryHandle {
    done: bool,
}

impl Letter {
    pub fn new(text: String) -> Self {
        Letter { text: text }
    }
}

impl Envelope {
    pub fn wrap(&mut self, letter: &Letter) {
        self.letter = Some(letter.clone());
    }
}

pub fn buy_prestamped_envelope() -> Envelope {
    Envelope { letter: None }
}

impl PickupLorryHandle {
    pub fn pickup(&mut self, _envelope: &Envelope) {
        // give letter
    }

    pub fn done(&mut self) {
        self.done = true;
        println!("sent");
    }
}

pub fn order_pickup() -> PickupLorryHandle {
    PickupLorryHandle { done: false }
}

fn main() {
    let letter = Letter::new(String::from("Dear RustFest"));
    let mut envelope = buy_prestamped_envelope();
    envelope.wrap(&letter);
    let mut lorry = order_pickup();
    lorry.pickup(&envelope);
    lorry.done();
}
1
sent

上面存在的问题:

Rust 中的 trait 系统

trait 是 Rust 的灵魂,Rust 中的所有抽象,如接口抽象,OOP 范式抽象,函数式范式抽象,都是基于 trait 完成的。

trait 是在行为上对类型的约束,这种约束让 trait 有如下四种用法:

Rust 中的析构顺序

一般来讲,变量的析构顺序和声明顺序相反,但是并不是所有的情况都是这样。

本地变量

本地变量先声明后析构。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
struct PrintDrop(&'static str);
impl Drop for PrintDrop {
    fn drop(&mut self) {
        println!("Dropping {}", self.0)
    }
}

fn main() {
    let _x = PrintDrop("x");
    let _y = PrintDrop("y");
}
1
2
Dropping y
Dropping x

元组

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
struct PrintDrop(&'static str);
impl Drop for PrintDrop {
    fn drop(&mut self) {
        println!("Dropping {}", self.0)
    }
}

fn main() {
    let _tup1 = (PrintDrop("x"), PrintDrop("y"));
    let _tup2 = (PrintDrop("s"), PrintDrop("z"));
}
1
2
3
4
Dropping s
Dropping z
Dropping x
Dropping y

先析构 tup2 ,后析构 tup1 ,在元组内部是前面的先析构,后面的后析构。

Rust 中的枚举

在 Rust 结构体中讲了枚举体也是代数数据类型,属于其中的和类型,满足加法原理。

使用枚举体来定义颜色。从而重构 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
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// 用枚举表示颜色
enum Color {
    Red,
    Yellow,
}

// 实现响应的方法
impl Color {
    fn to_fg_str(&self) -> &str {
        match *self {
            Color::Red => "31",
            Color::Yellow => "33",
        }
    }

    fn to_bg_str(&self) -> &str {
        match *self {
            Color::Red => "41",
            Color::Yellow => "43",
        }
    }
}

use std::convert::From;
use std::str::FromStr;
use std::string::String;

impl<'a> From<&'a str> for Color {
    fn from(src: &str) -> Self {
        src.parse().unwrap_or(Color::Red)
    }
}

impl From<String> for Color {
    fn from(src: String) -> Self {
        src.parse().unwrap_or(Color::Red)
    }
}

impl FromStr for Color {
    type Err = ();
    fn from_str(src: &str) -> Result<Self, Self::Err> {
        let src = src.to_lowercase();
        match src.as_ref() {
            "red" => Ok(Color::Red),
            "yellow" => Ok(Color::Yellow),
            _ => Err(()),
        }
    }
}

struct ColoredString {
    input: String,
    fgcolor: Option<Color>,
    bgcolor: Option<Color>,
}

trait Colorize {
    fn red(self) -> ColoredString;
    fn yellow(self) -> ColoredString;
    fn color<S: Into<Color>>(self, color: S) -> ColoredString;

    fn on_red(self) -> ColoredString;
    fn on_yellow(self) -> ColoredString;
    fn on_color<S: Into<Color>>(self, color: S) -> ColoredString;
}

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

// 为 ColoredString 实现 Colorize trait

impl<'a> Colorize for ColoredString {
    fn red(self) -> ColoredString {
        self.color(Color::Red)
    }

    fn yellow(self) -> ColoredString {
        self.color(Color::Yellow)
    }

    fn on_red(self) -> ColoredString {
        self.on_color(Color::Red)
    }

    fn on_yellow(self) -> ColoredString {
        self.on_color(Color::Yellow)
    }

    fn color<S: Into<Color>>(self, color: S) -> ColoredString {
        ColoredString {
            fgcolor: Some(color.into()),
            ..self
        }
    }

    fn on_color<S: Into<Color>>(self, color: S) -> ColoredString {
        ColoredString {
            bgcolor: Some(color.into()),
            ..self
        }
    }
}

impl<'a> Colorize for &'a str {
    fn red(self) -> ColoredString {
        self.color(Color::Red)
    }

    fn yellow(self) -> ColoredString {
        self.color(Color::Yellow)
    }

    fn on_red(self) -> ColoredString {
        self.on_color(Color::Red)
    }

    fn on_yellow(self) -> ColoredString {
        self.on_color(Color::Yellow)
    }

    fn color<S: Into<Color>>(self, color: S) -> ColoredString {
        ColoredString {
            fgcolor: Some(color.into()),
            input: String::from(self),
            ..ColoredString::default()
        }
    }

    fn on_color<S: Into<Color>>(self, color: S) -> ColoredString {
        ColoredString {
            bgcolor: Some(color.into()),
            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 let Some(ref bgcolor) = self.bgcolor {
            res.push_str(bgcolor.to_bg_str());
            has_wrote = true;
        }
        if let Some(ref fgcolor) = self.fgcolor {
            if has_wrote {
                res.push_str(";");
            }
            res.push_str(fgcolor.to_fg_str());
        }
        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);
}
1
Hello

Rust 中的结构体

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

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