使用结构体来组织相关数据
Using Structs to Structure Related Data
“结构体”(struct 或 structure)是一种自定义数据类型,它允许你将多个相关的、构成一个有意义组的值打包并命名。如果你熟悉面向对象的语言,结构体就像对象的“数据属性”。在本章中,我们将比较元组与结构体,在现有知识的基础上,展示何时结构体是更好的数据分组方式。
A struct, or structure, is a custom data type that lets you package together and name multiple related values that make up a meaningful group. If you’re familiar with an object-oriented language, a struct is like an object’s data attributes. In this chapter, we’ll compare and contrast tuples with structs to build on what you already know and demonstrate when structs are a better way to group data.
我们将演示如何定义和实例化结构体。我们将讨论如何定义关联函数,特别是称为“方法”(methods)的那类关联函数,以指定与结构体类型相关联的行为。结构体和枚举(在第 6 章中讨论)是为你程序的领域创建新类型的构建块,以充分利用 Rust 的编译时类型检查。
We’ll demonstrate how to define and instantiate structs. We’ll discuss how to define associated functions, especially the kind of associated functions called methods, to specify behavior associated with a struct type. Structs and enums (discussed in Chapter 6) are the building blocks for creating new types in your program’s domain to take full advantage of Rust’s compile-time type checking.