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:56:31Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 0226216f7782e55712c8c583b06280c38483c093b9b4ef501b1c95f09eb2514a source_path: ch08-00-common-collections.md workflow: 16

常用集合 (Common Collections)

Common Collections

Rust 的标准库包含许多非常有用的数据结构,称为“集合 (collections)”。大多数其他数据类型代表一个特定的值,但集合可以包含多个值。与内置的数组和元组类型不同,这些集合指向的数据存储在堆上,这意味着数据量不需要在编译时已知,并且可以随着程序的运行而增长或缩小。每种集合都有不同的功能和成本,为当前情况选择合适的集合是你随着时间的推移会培养的一种技能。在本章中,我们将讨论在 Rust 程序中经常使用的三种集合:

Rust’s standard library includes a number of very useful data structures called collections. Most other data types represent one specific value, but collections can contain multiple values. Unlike the built-in array and tuple types, the data that these collections point to is stored on the heap, which means the amount of data does not need to be known at compile time and can grow or shrink as the program runs. Each kind of collection has different capabilities and costs, and choosing an appropriate one for your current situation is a skill you’ll develop over time. In this chapter, we’ll discuss three collections that are used very often in Rust programs:

  • “向量 (vector)” 允许你在相邻位置存储可变数量的值。

  • “字符串 (string)” 是字符的集合。我们之前提到过 String 类型,但在本章中,我们将深入讨论它。

  • “哈希映射 (hash map)” 允许你将一个值与一个特定的键关联起来。它是更通用的数据结构“映射 (map)”的一种特定实现。

  • A vector allows you to store a variable number of values next to each other.

  • A string is a collection of characters. We’ve mentioned the String type previously, but in this chapter, we’ll talk about it in depth.

  • A hash map allows you to associate a value with a specific key. It’s a particular implementation of the more general data structure called a map.

要了解标准库提供的其他种类的集合,请参阅文档

To learn about the other kinds of collections provided by the standard library, see the documentation.

我们将讨论如何创建和更新向量、字符串和哈希映射,以及各自的特别之处。

We’ll discuss how to create and update vectors, strings, and hash maps, as well as what makes each special.