In this chapter:
- Composing data with structs
- Creating enumerated data types
- Add methods to types
- Handling errors in a type-safe manner
- Defining and implementing common behavior with traits
- Understanding how to keep implementation details private
- Using cargo to build documentation
Welcome to chapter 3. If we spent the last chapter looking at Rust’s atoms, this chapter is focused more on its molecules.
This chapter focuses on two key building blocks for Rust programmers, struct and enum. Both are forms of compound data types. That is, both struct and enum can compose other types together to create something more useful than those other types would be alone. Consider how a 2D point (x, y) is composed from two numbers, x and y. We wouldn’t want to maintain two variables x and y in our program. Instead, we would like to refer to the point as a whole entity.
We also discuss how to add methods to types with impl blocks. Lastly, we take a good look at traits, Rust’s system for defining interfaces.[32]
Throughout this chapter, you’ll be working through how to represent files in code. Although conceptually simple—if you’re reading this book, it’s highly likely you’ve interacted with a file through code before—there are enough edge cases to make things interesting.