Chapter 16. Collections
We all behave like Maxwellâs demon. Organisms organize. In everyday experience lies the reason sober physicists across two centuries kept this cartoon fantasy alive. We sort the mail, build sand castles, solve jigsaw puzzles, separate wheat from chaff, rearrange chess pieces, collect stamps, alphabetize books, create symmetry, compose sonnets and sonatas, and put our rooms in order, and all this we do requires no great energy, as long as we can apply intelligence.
James Gleick, The Information: A History, a Theory, a Flood
The Rust standard library contains several collections, generic types for storing data in memory. Weâve already been using collections, such as Vec
and HashMap
, throughout this book. In this chapter, weâll cover the methods of these two types in detail, along with the other half-dozen standard collections. Before we begin, letâs address a few systematic differences between Rustâs collections and those in other languages.
First, moves and borrowing are everywhere. Rust uses moves to avoid deep-copying values. Thatâs why the method Vec<T>::push(item)
takes its argument by value, not by reference. The value is moved into the vector. The diagrams in Chapter 4 show how this works out in practice: pushing a Rust String
to a Vec<String>
is quick, because Rust doesnât have to copy the stringâs character data, and ownership of the string is always clear.
Second, Rust doesnât have invalidation errorsâthe kind of dangling-pointer ...
Get Programming Rust, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.