使用结构体的示例程序

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

让我们使用 Cargo 创建一个新的二进制项目,名为 rectangles,它将接受以像素为单位指定的矩形的宽度和高度,并计算矩形的面积。清单 5-8 展示了一个简短的程序,它在项目的 src/main.rs 中使用了一种方法来完成这项工作。

文件名:src/main.rs

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
}

清单 5-8:计算由单独的宽度和高度变量指定的矩形面积

现在,使用 cargo run 运行此程序

$ cargo run
   Compiling rectangles v0.1.0 (file:///projects/rectangles)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s
     Running `target/debug/rectangles`
The area of the rectangle is 1500 square pixels.

这段代码成功地通过调用带有每个维度的 area 函数来计算矩形的面积,但我们可以做得更多,使这段代码更清晰易读。

这段代码的问题在 area 的签名中很明显

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
}

area 函数应该计算一个矩形的面积,但我们编写的函数有两个参数,并且在我们的程序中任何地方都没有明确指出这些参数是相关的。将宽度和高度组合在一起会更具可读性和可管理性。我们已经在 “元组类型” 中讨论了一种可能的方法第 3 章的章节:通过使用元组。

使用元组进行重构

清单 5-9 展示了我们程序的另一个版本,它使用了元组。

文件名:src/main.rs

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
}

清单 5-9:使用元组指定矩形的宽度和高度

在某种程度上,这个程序更好。元组让我们添加了一些结构,并且我们现在只传递一个参数。但在另一方面,这个版本不太清晰:元组不命名它们的元素,所以我们必须索引到元组的各个部分,使我们的计算不太明显。

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

使用结构体重构:添加更多含义

我们使用结构体通过标记数据来添加含义。我们可以将我们正在使用的元组转换为结构体,为整体以及各个部分命名,如清单 5-10 所示。

文件名:src/main.rs

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
}

清单 5-10:定义 Rectangle 结构体

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

我们的 area 函数现在定义了一个参数,我们将其命名为 rectangle,其类型是结构体 Rectangle 实例的不可变借用。正如第 4 章中提到的,我们希望借用结构体而不是获取其所有权。这样,main 保留其所有权并可以继续使用 rect1,这就是我们在函数签名和调用函数的地方使用 & 的原因。

area 函数访问 Rectangle 实例的 widthheight 字段(请注意,访问借用的结构体实例的字段不会移动字段值,这就是为什么您经常看到结构体的借用)。我们现在的 area 函数签名确切地说明了我们的意思:计算 Rectangle 的面积,使用其 widthheight 字段。这表明宽度和高度彼此相关,并为这些值提供了描述性名称,而不是使用元组索引值 01。这对清晰度来说是一个胜利。

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

在调试程序时,能够打印 Rectangle 的实例并查看其所有字段的值将非常有用。清单 5-11 尝试使用 println!正如我们在之前的章节中使用过的那样。然而,这行不通。

文件名:src/main.rs

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

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

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

清单 5-11:尝试打印 Rectangle 实例

当我们编译这段代码时,我们得到了一个错误,其核心消息如下

error[E0277]: `Rectangle` doesn't implement `std::fmt::Display`

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

如果我们继续阅读错误,我们会发现这个有用的提示

   = 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

让我们试试看!println! 宏调用现在看起来像 println!("rect1 is {rect1:?}");。将说明符 :? 放在花括号内告诉 println! 我们想要使用称为 Debug 的输出格式。Debug trait 使我们能够以对开发者有用的方式打印我们的结构体,以便我们在调试代码时可以看到它的值。

使用此更改编译代码。糟糕!我们仍然收到错误

error[E0277]: `Rectangle` doesn't implement `Debug`

但是,编译器再次给了我们一个有用的提示

   = help: the trait `Debug` is not implemented for `Rectangle`
   = note: add `#[derive(Debug)]` to `Rectangle` or manually `impl Debug for Rectangle`

Rust 确实 包含打印调试信息的功能,但我们必须显式选择启用该功能以供我们的结构体使用。为此,我们在结构体定义之前添加外部属性 #[derive(Debug)],如清单 5-12 所示。

文件名:src/main.rs

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

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

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

清单 5-12:添加属性以派生 Debug trait 并使用调试格式打印 Rectangle 实例

现在,当我们运行程序时,我们不会收到任何错误,并且我们将看到以下输出

$ cargo run
   Compiling rectangles v0.1.0 (file:///projects/rectangles)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s
     Running `target/debug/rectangles`
rect1 is Rectangle { width: 30, height: 50 }

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

$ cargo run
   Compiling rectangles v0.1.0 (file:///projects/rectangles)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s
     Running `target/debug/rectangles`
rect1 is Rectangle {
    width: 30,
    height: 50,
}

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

注意:调用 dbg! 宏会打印到标准错误控制台流 (stderr),而不是 println!,后者会打印到标准输出控制台流 (stdout)。我们将在 第 12 章的 “将错误消息写入标准错误而不是标准输出” 节中详细讨论 stderrstdout.

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

#[derive(Debug)]
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 的引用。以下是此示例的输出

$ cargo run
   Compiling rectangles v0.1.0 (file:///projects/rectangles)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.61s
     Running `target/debug/rectangles`
[src/main.rs:10:16] 30 * scale = 60
[src/main.rs:14:5] &rect1 = Rectangle {
    width: 60,
    height: 50,
}

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

除了 Debug trait 之外,Rust 还提供了一些 trait 供我们与 derive 属性一起使用,这些 trait 可以为我们的自定义类型添加有用的行为。这些 trait 及其行为在 附录 C 中列出。我们将在第 10 章中介绍如何使用自定义行为实现这些 trait,以及如何创建您自己的 trait。除了 derive 之外,还有许多其他属性;有关更多信息,请参阅 Rust 参考手册的 “属性” 章节

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