Chapter 9. Structs
Long ago, when shepherds wanted to see if two herds of sheep were isomorphic, they would look for an explicit isomorphism.
John C. Baez and James Dolan, “Categorification”
Rust structs resemble struct types in C and C++, classes in Python, and objects in JavaScript. A struct assembles several values of assorted types together into a single value so you can deal with them as a unit. Given a struct, you can read and modify its individual components. And a struct can have methods associated with it that operate on its components.
In this chapter, we’ll explain in detail how structs are defined, how they are used, and what they look like in memory. We’ll cover how to add methods to them, how to define generic struct types that work with many different component types, and how to ask Rust to generate some handy methods for your structs.
Defining Structs
The most common way to define a struct type looks like this:
/// A rectangle of eight-bit grayscale pixels.structGrayscaleMap ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access