使用结构体的示例程序
为了理解何时可能需要使用结构体,让我们编写一个计算矩形面积的程序。我们将从使用单个变量开始,然后重构程序,直到我们改为使用结构体。
让我们用 Cargo 创建一个新的二进制项目,名为 rectangles,它将获取以像素为单位指定的矩形的宽度和高度,并计算矩形的面积。列表 5-8 展示了一个简短的程序,它在我们的项目的 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 }
现在,使用 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 显示了使用元组的程序的另一个版本。
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 }
在某种程度上,这个程序更好。元组允许我们添加一些结构,并且我们现在只传递一个参数。但在另一方面,此版本不太清晰:元组不命名其元素,因此我们必须索引到元组的各个部分,这使得我们的计算不太明显。
混合宽度和高度对于面积计算无关紧要,但是如果我们想在屏幕上绘制矩形,它就很重要了!我们必须记住 width
是元组索引 0
,height
是元组索引 1
。如果其他人要使用我们的代码,这将更难理解和记住。因为我们没有在代码中传达数据的含义,所以现在更容易引入错误。
使用结构体重构:添加更多含义
我们使用结构体通过标记数据来添加含义。我们可以将我们正在使用的元组转换为一个结构体,其中包含整个结构的名称以及各部分的名称,如列表 5-10 所示。
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
结构体在这里,我们定义了一个结构体,并将其命名为 Rectangle
。在花括号内,我们将字段定义为 width
和 height
,它们的类型都是 u32
。然后,在 main
中,我们创建了一个 Rectangle
的特定实例,其宽度为 30
,高度为 50
。
现在,我们的 area
函数定义了一个参数,我们将其命名为 rectangle
,其类型是结构体 Rectangle
实例的不可变借用。正如在第 4 章中提到的那样,我们希望借用结构体而不是取得其所有权。这样,main
会保留其所有权,并且可以继续使用 rect1
,这就是我们在函数签名中使用 &
并在调用函数的位置使用它的原因。
area
函数访问 Rectangle
实例的 width
和 height
字段(请注意,访问借用的结构体实例的字段不会移动字段值,这就是您经常看到结构体借用的原因)。我们现在用于 area
的函数签名准确地表达了我们的意思:使用 Rectangle
的 width
和 height
字段来计算其面积。这表明宽度和高度彼此相关,并且为这些值提供了描述性名称,而不是使用元组索引值 0
和 1
。这是清晰性方面的胜利。
通过派生 trait 添加有用的功能
在调试程序时能够打印 Rectangle
的实例并查看其所有字段的值将会很有用。列表 5-11 尝试使用println!
宏正如我们在之前的章节中使用的那样。但这不起作用。
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {}", rect1);
}
Rectangle
实例当我们编译此代码时,我们会收到一个错误,其中包含此核心消息
error[E0277]: `Rectangle` doesn't implement `std::fmt::Display`
println!
宏可以进行多种格式化,默认情况下,花括号告诉 println!
使用称为 Display
的格式:用于直接最终用户消费的输出。到目前为止,我们看到的原始类型默认实现 Display
,因为只有一种方法可以向用户显示 1
或任何其他原始类型。但是对于结构体,println!
应如何格式化输出不太清楚,因为有更多的显示可能性:您是否需要逗号?您是否要打印花括号?是否应显示所有字段?由于这种歧义,Rust 不会尝试猜测我们想要什么,并且结构体没有提供与 println!
和 {}
占位符一起使用的 Display
实现。
如果我们继续阅读错误,我们会发现这个有用的注释
= 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 所示。
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!("rect1 is {rect1:?}"); }
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
),而不是打印到标准输出控制台流 (stdout
) 的 println!
。我们将在第 12 章的“将错误消息写入标准错误而不是标准输出”部分中详细讨论 stderr
和 stdout
.
这是一个示例,我们对分配给 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 还为我们提供了许多可以使用 derive
属性的 trait,这些 trait 可以为我们的自定义类型添加有用的行为。这些 trait 及其行为在附录 C中列出。我们将在第 10 章中介绍如何实现具有自定义行为的这些 trait 以及如何创建自己的 trait。除了 derive
之外,还有许多其他属性;有关更多信息,请参阅Rust 参考的“属性”部分。
我们的 area
函数非常具体:它只计算矩形的面积。将此行为与我们的 Rectangle
结构体更紧密地联系起来会很有帮助,因为它不适用于任何其他类型。让我们看看如何通过将 area
函数转换为在我们的 Rectangle
类型上定义的 area
*方法* 来继续重构此代码。