sui_rust/ch02/
s6_paradigms.rs

1//! 第二章:Rust核心概念
2//! 2.5 编程范式:面向编译器编程
3//!
4//! 讨论:
5//!
6//! 1. Rust 是 FP 语言吗?
7//! 2. Rust 是 OOP 语言吗?
8//! 3. 如果都不是,那 Rust 是面向啥的语言 ? 面向编译器。
9//!
10//!
11
12/**
13
14    ### Rust 是面向对象语言吗?
15
16    OOP style:
17
18    1. 支持面向接口编程
19    2. 支持封装
20    3. 不支持继承(但可以模拟)
21
22    ```
23    interface Foo {}
24    class Bar: Foo {
25        //Implement Foo here
26    }
27    ```
28
29    ```rust
30    trait Foo {}
31    struct Bar;
32    impl Bar;
33    impl Foo for Bar {}
34    ```
35
36    ### Rust 是函数式语言吗?
37
38    函数式style:
39    1. 默认不可变(但也支持可变)
40    2. 支持递归(但不支持尾递归优化)
41    3. 函数是一等公民,高阶函数支持(有限)
42    4. 和类型/ 积类型 (Option/Result)
43
44    ```rust
45    fn get_sum(mut total: u32, mut i: u32) -> u32 {
46        if i > 10000000 {
47            return total;
48        }
49
50        total = total.wrapping_add(i);
51        i += 1;
52        get_sum(total, i)
53    }
54    fn main() {
55        let total = 0;
56        let total = get_sum(total, 1);
57        println!("{}", total);
58    }
59
60    ```
61
62    curring:
63
64    ```
65    #[derive(Debug)]
66    struct States<'a> {
67        a: &'a i32,
68        b: &'a i32,
69    }
70
71    trait Currying {
72        type ReturnType: Fn(i32) -> i32;
73        fn add(self) -> Self::ReturnType;
74    }
75
76    impl Currying for States<'static>{
77        type ReturnType = Box<dyn Fn(i32) -> i32>;
78
79        fn add(self) -> Self::ReturnType {
80            Box::new(move|x| {
81                x * self.a
82            })
83        }
84    }
85
86    let r_value: States = States {
87        a: &100,
88        b: &100
89    };
90
91    let r1 = r_value.add();
92    let r2 = r1(5);
93
94    assert_eq!(500, r2);
95    ```
96
97    ### Rust 是 面向编译器 编程的语言
98
99    ```text
100    +----------------------------------------------------+
101    |                crate                               |
102    |                                                    |
103    |      +-----------------------------------+         |
104    |      |           std                     |         |
105    |      |                                   |         |
106    |      |       +---------------------+     |         |
107    |      |       |                     |     |         |
108    |      |       |     core            |     |         |
109    |      |       |    +----------+     |     |         |
110    |      |       |    | compiler |     |     |         |
111    |      |       |    +----------+     |     |         |
112    |      |       |                     |     |         |
113    |      |       +---------------------+     |         |
114    |      |                                   |         |
115    |      |                                   |         |
116    |      +-----------------------------------+         |
117    |                                                    |
118    |                                                    |
119    +----------------------------------------------------+
120
121    ```
122
123    查看 Rust 源码组织结构: [https://github.com/rust-lang/rust](https://github.com/rust-lang/rust)
124
125    洋葱模型:
126
127    1. 最小内核所谓所有权和借用规则,就是编译器特性
128    2. 基于最小内核开始构造了 core
129    3. 基于core 构造了 std
130    4. 基于 std 构造生态 crate
131    5. 命令式编程为主(类 C),OOP 和 FP Style 辅助
132
133    典型的实现:[std::cell::Cell](https://github.com/rust-lang/rust/blob/master/library/core/src/cell.rs)
134
135    Cell 的语义:
136
137    1. 在不可变引用的基础上构造一个安全的内部可变性
138    2. 只针对实现 Copy 的类型提供 get 方法
139    3. 对于 非 Copy 的类型,提供 move out 的方法
140
141    ```rust
142
143    #[stable(feature = "rust1", since = "1.0.0")]
144    #[repr(transparent)]
145    pub struct Cell<T: ?Sized> {
146        value: UnsafeCell<T>,
147    }
148
149    #[stable(feature = "rust1", since = "1.0.0")]
150    unsafe impl<T: ?Sized> Send for Cell<T> where T: Send {}
151
152    #[stable(feature = "rust1", since = "1.0.0")]
153    impl<T: ?Sized> !Sync for Cell<T> {}
154
155    #[stable(feature = "rust1", since = "1.0.0")]
156    impl<T: Copy> Clone for Cell<T> {
157        #[inline]
158        fn clone(&self) -> Cell<T> {
159            Cell::new(self.get())
160        }
161    }
162
163    impl<T: Eq + Copy> Eq for Cell<T> {}
164
165    impl<T> Cell<T> {
166
167        pub const fn new(value: T) -> Cell<T> {
168            Cell { value: UnsafeCell::new(value) }
169        }
170
171        pub fn set(&self, val: T) {
172            let old = self.replace(val);
173            drop(old);
174        }
175    }
176
177    impl<T: Copy> Cell<T> {
178        pub fn get(&self) -> T {
179            // SAFETY: This can cause data races if called from a separate thread,
180            // but `Cell` is `!Sync` so this won't happen.
181            unsafe { *self.value.get() }
182        }
183    }
184
185    impl<T: Default> Cell<T> {
186        #[stable(feature = "move_cell", since = "1.17.0")]
187        pub fn take(&self) -> T {
188            self.replace(Default::default())
189        }
190    }
191    ```
192*/
193pub fn compiler_oriented_programming() {
194    println!("Compiler-Oriented Programming")
195}