Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help


x-i18n: generated_at: “2026-03-01T13:42:29Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: f868f22d0149966b0d0b7191ce20318bf12981275cb0e393dbcd52caaab8b173 source_path: ch05-00-structs.md workflow: 16

使用结构体组织相关数据 (Using Structs to Structure Related Data)

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.

我们将演示如何定义和实例化结构体。我们将讨论如何定义关联函数 (associated functions),特别是被称为“方法 (methods)”的一类关联函数,以指定与结构体类型相关联的行为。结构体和枚举 (enums)(在第 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.