【Rust学习】05_2 使用结构体的代码示例

前言

为了了解我们何时可能想要使用结构体,让我们编写一个计算长方形面积的程序。我们将从使用单个变量开始,然后重构程序,直到我们改用结构体。

内容

现在让我们使用 Cargo 新建一个叫做 rectangles 的程序,它获取以像素为单位的长方形的宽度和高度,并计算出长方形的面积。

基础代码

fn main() {
    let width1 = 30;
    let height1 = 50;
    println!("The area of the rectangle is {} square pixels.", area(width1, height1));
}

fn area(width: u32, height: u32) -> u32 {
    width * height
}

运行代码:

/Users/wangyang/.cargo/bin/cargo run --color=always --profile dev --package rectangles --bin rectangles
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/rectangles`
The area of the rectangle is 1500 square pixels.

此代码通过对每个维度调用 area 函数成功地计算出矩形的面积,但我们可以做更多工作来使此代码清晰可读。

fn area(width: u32, height: u32) -> u32 {

area 函数应该计算一个长方形的面积,但我们编写的函数有两个参数,并且在我们的程序中的任何位置都不清楚这些参数是否相关。将 width 和 height 组合在一起会更具可读性和更易于管理,所以我们使用元组(Tuples)来进行重构;

重构代码

使用元组重构

现在让我们来一起看看使用元组(Tuples)重构后的代码:

fn main() {
    let rect1 = (30, 50);
    println!("The area of the rectangle is {} square pixels.", area(rect1))
}

fn  area(dimensions: (u32, u32)) -> u32 {
    dimensions.0 * dimensions.1
}

在某种程度上,这个程序更好。Tuples 让我们添加一些结构,我们现在只传递一个参数。但从另一个方面来说,这个版本就不那么清楚了:元组不命名它们的元素,所以我们必须对元组的各个部分进行索引,使我们的计算不那么明显。

混合宽度和高度对于面积计算无关紧要,但如果我们想在屏幕上绘制矩形,那就很重要了!我们必须记住,width 是元组索引 0,height 是元组索引 1。如果其他人使用我们的代码,这将更难弄清楚并记住。因为我们没有在代码中传达数据的含义,所以现在更容易引入错误。

使用结构体重构

我们使用结构体通过标记数据来添加含义。我们可以将正在使用的元组转换为一个结构体,该结构体具有整体名称,部分也具有名称,代码如下:

struct Rectangle {
    width: u32,
    height: u32,
}
fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };
    println!("The area of the rectangle is {} square pixels.", area(&rect1))
}

fn area(rectangle: &Rectangle) -> u32 {
    rectangle.width * rectangle.height
}

在这里,我们定义了一个结构并将其命名为 Rectangle。在大括号内,我们将字段定义为 widthheight,这两个字段的类型都是 u32。然后,在 main 中,我们创建了一个特定的 Rectangle 实例,它的宽度为 30,高度为 50

我们的 area 函数现在使用一个参数定义,我们将其命名为 rectangle,其类型是 struct Rectangle 实例的不可变借用。我们想要借用结构体而不是获得它的所有权。这样,main保留了其所有权,并可以继续使用rect1,这就是我们在函数签名中使用&的原因,也是我们调用函数的地方。

area 函数访问 Rectangle 实例的 widthheight 字段(请注意,访问借用的结构实例的字段不会移动字段值,这就是您经常看到结构借用的原因)。我们的 area 函数签名现在准确地说明了我们的意思:使用 Rectangle 的 widthheight 字段计算 Rectangle 的面积。这传达了 width 和 height 彼此相关,并且它为值提供了描述性名称,而不是使用 01 的 Tuples 索引值。这是一场清晰的胜利。

使用派生Traits添加有用的功能

如果我们在调试程序时能够打印 Rectangle 的实例并查看其所有字段的值,那将非常有用。现在我们来尝试打印一下:

struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    println!("rect1 is {}", rect1);
}

哦吼,很明显我们得到了一个报错:

error[E0277]: `Rectangle` doesn't implement `std::fmt::Display`
  --> src/main.rs:53:29
   |
53 |     println!("rect1 is {}", rect1);
   |                             ^^^^^ `Rectangle` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `Rectangle`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

println! 宏可以执行多种格式设置,默认情况下,大括号指示 println! 使用称为 Display: 输出的格式,供最终用户直接使用。到目前为止,我们所看到的基元类型默认实现 Display,因为只有一种方式可以向用户显示 1 或任何其他基元类型。但是对于结构体,println!应该格式化输出的方式就不那么清楚了,因为有更多的显示可能性:是否需要逗号?是否要打印大括号?是否应显示所有字段?由于这种歧义,Rust 不会尝试猜测我们想要什么,并且结构体没有提供的 Display 实现来与 println!{} 占位符一起使用。

根据上面的提示,现在让我们试试以下操作!println! 宏调用现在将类似于 println!("rect1 is {rect1:?}"); 。将说明符 :? 放在大括号内表示 println!我们想要使用一种称为 Debug 的输出格式。Debug trait 使我们能够以对开发人员有用的方式打印我们的结构体,这样我们就可以在调试代码时看到它的值。

很棒,现在我们得到了另一个错误:

error[E0277]: `Rectangle` doesn't implement `Debug`
  --> src/main.rs:54:24
   |
54 |     println!("rect1 is {rect1:?}");
   |                        ^^^^^^^^^ `Rectangle` cannot be formatted using `{:?}`
   |
   = help: the trait `Debug` is not implemented for `Rectangle`
   = note: add `#[derive(Debug)]` to `Rectangle` or manually `impl Debug for Rectangle`
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider annotating `Rectangle` with `#[derive(Debug)]`
   |
42 + #[derive(Debug)]
43 | struct Rectangle {
   |

不过我们也得到了有用的信息,Rust 确实包含打印调试信息的功能,但我们必须明确选择使该功能可用于我们的结构体。为此,我们在结构体定义之前添加外部属性 #[derive(Debug)]

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    // println!("rect1 is {}", rect1);
    println!("rect1 is {rect1:?}");
}

现在我们再次尝试运行这个代码,看看有什么结果:

/Users/wangyang/.cargo/bin/cargo run --color=always --profile dev --package rectangles --bin rectangles
warning: fields `width` and `height` are never read
  --> src/main.rs:44:5
   |
43 | struct Rectangle {
   |        --------- fields in this struct
44 |     width: u32,
   |     ^^^^^
45 |     height: u32,
   |     ^^^^^^
   |
   = note: `Rectangle` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
   = note: `#[warn(dead_code)]` on by default

warning: `rectangles` (bin "rectangles") generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/rectangles`
rect1 is Rectangle { width: 30, height: 50 }

Process finished with exit code 0

好的,现在我们正常打印出来了,但是同时我们也收到了一个警告,不过我们的却是定义了但是没有去读取和使用,所以这个警告是正常的,如果不想看到,那该怎么办呢,同样的道理,我们在结构体定义之前添加外部属性 #[allow(dead_code)]

#[derive(Debug)] #[allow(dead_code)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    // println!("rect1 is {}", rect1);
    println!("rect1 is {rect1:?}");
}

现在再次进行编译:

/Users/wangyang/.cargo/bin/cargo run --color=always --profile dev --package rectangles --bin rectangles
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/rectangles`
rect1 is Rectangle { width: 30, height: 50 }

Process finished with exit code 0

完美!这不是最漂亮的输出,但它显示了此实例的所有字段的值,这肯定会在调试过程中有所帮助。当我们有更大的结构体时,拥有更易于阅读的输出是很有用的;在这些情况下,我们可以在 println! 字符串中使用 {:#?} 而不是 {:?}。在此示例中,使用 {:#?} 样式将输出以下内容:

/Users/wangyang/.cargo/bin/cargo run --color=always --profile dev --package rectangles --bin rectangles
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/rectangles`
rect1 is Rectangle {
    width: 30,
    height: 50,
}

Process finished with exit code 0

使用 Debug 格式打印出值的另一种方法是使用 dbg!宏,它获取表达式的所有权(与 println!相反,它采用引用),打印该 dbg! 宏调用的文件和行号与该表达式的结果值一起在代码中发生,并返回该值的所有权。

注意:调用 dbg!宏将打印到标准错误控制台流 (stderr),而 println! 将打印到标准输出控制台流 (stdout)。

下面是一个示例,我们对分配给 width 字段的值以及 rect1 中整个结构体的值感兴趣:

#[derive(Debug)] #[allow(dead_code)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let scale = 2;
    let rect1 = Rectangle {
        width: dbg!(30 * scale),
        height: 50,
    };

    dbg!(&rect1);
}

我们可以将 dbg! 放在表达式 30 * scale 周围,因为 dbg! 返回表达式值的所有权,所以 width 字段将获得与我们没有 dbg! 调用相同的值。我们不希望 dbg! 获得 rect1 的所有权,因此我们在下一次调用中使用对 rect1 的引用。此示例的输出如下所示:

/Users/wangyang/.cargo/bin/cargo run --color=always --profile dev --package rectangles --bin rectangles
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/rectangles`
[src/main.rs:68:16] 30 * scale = 60
[src/main.rs:72:5] &rect1 = Rectangle {
    width: 60,
    height: 50,
}

我们可以看到输出的第一位来自 src/main.rs 第 68行,我们正在调试表达式 30 * scale,其结果值为 60(为整数实现的 Debug 格式是仅打印它们的值)。src/main.rs 第 72 行的 dbg! 调用输出 &rect1 的值,即 Rectangle 结构。此输出使用 Rectangle 类型的漂亮 Debug 格式。dbg! 宏在你试图弄清楚你的代码在做什么时真的非常有用!

除了 Debug trait 之外,Rust 还为我们提供了许多 trait 供我们使用 derive 属性,这些 trait 可以为我们的自定义类型添加有用的行为。后续我们将介绍如何使用自定义行为实施这些特征,以及如何创建自己的特征。除了 derive 之外,还有许多属性;

我们的 area 函数非常具体:它只计算长方形的面积。将此行为更紧密地绑定到我们的 Rectangle 结构体会很有帮助,因为它不适用于任何其他类型的结构。让我们看看如何通过将 area 函数转换为在 Rectangle 类型上定义的 area方法来继续重构此代码。

posted @ 2024-09-12 13:48:23 王洋 阅读(47) 评论(0)
发表评论
昵称
邮箱
网址