study_rust_example/struct_related/
retangle.rs

1//! **{:?}pretty-print打印时候没有实现`Rectangle` doesn't implement `Debug`**
2//! 定义矩形结构体,具有高和宽的属性
3//
4#[derive(Debug)]
5pub struct Rectangle {
6    width: i32,
7    height: i32,
8}
9
10impl Rectangle {
11    /// 计算矩形的面积
12    /// - 示例如下
13    /// ```
14    ///     let mut rect = Rectangle {
15    ///         width: 12,
16    ///         height: 8,
17    ///     };
18    ///     let area_val = rect.area();
19    /// ```
20    pub fn area(&self) -> i32 {
21        self.width * self.height
22    }
23
24    /// 获取矩形的宽
25    /// **move了所有权,调用之后,后续该实例就没法使用;**
26    /// - 示例如下
27    /// ```
28    ///     let mut rect = Rectangle {
29    ///         width: 12,
30    ///         height: 8,
31    ///     };
32    ///     let width = rect.get_width();
33    /// ```
34    pub fn get_width(self) -> i32 {
35        self.width
36    }
37
38    /// 更新矩形的宽
39    /// - 示例如下
40    /// ```
41    ///     let mut rect = Rectangle {
42    ///         width: 12,
43    ///         height: 8,
44    ///     };
45    ///     rect.modify_width(-32);
46    ///
47    pub fn modify_width(&mut self, new_width: i32) {
48        self.width = new_width;
49    }
50
51    /// 判断矩形的宽是否合法
52    /// - 示例如下
53    /// ```
54    ///     let mut rect = Rectangle {
55    ///         width: 12,
56    ///         height: 8,
57    ///     };
58    ///     if rect.valid_width() {
59    ///         println!("width valid.");
60    ///     }
61    ///
62    fn valid_width(self: &Self) -> bool {
63        self.width > 0
64    }
65
66    /// 生成正方形
67    /// - 示例如下
68    /// ```
69    /// let square_val = Rectangle::square(10);
70    /// println!("square: {:?}", square_val);
71    ///
72    // Associated function,类似于静态方法?
73    pub fn square(size: i32) -> Self {
74        Self {
75            width: size,
76            height: size,
77        }
78    }
79}
80
81pub fn retangle_struct_study() {
82    let mut rect = Rectangle {
83        width: 12,
84        height: 8,
85    };
86    let area_val = rect.area();
87    // 直接打印没有实现标准的std::fmt::Display
88    println!("area val {}, rect {:?}", area_val, rect);
89    if rect.valid_width() {
90        println!("width valid.");
91    }
92    rect.modify_width(-32);
93    println!("area after modify val {}, rect {:?}", rect.area(), rect);
94    let square_val = Rectangle::square(10);
95    println!("square: {:?}", square_val);
96    println!("rect width {}", rect.get_width());
97    // error[E0382]: borrow of moved value: `rect`
98    // rect.area();
99}