chapter three

3 Compound Data Types

 

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.

3.1 Using plain functions to experiment with an API

3.2 Modelling files with struct

3.3 Adding Methods to a struct with impl

3.3.1 Simplifying object creation by implementing a new() method

3.4 Returning errors

3.4.1 Modifying a known global variable

3.4.2 Making use of the Result return type

3.5 Defining and making use of enum

3.5.1 Using an enum to manage internal state

3.6 Defining Common Behavior with Traits

3.6.1 Creating a Read trait

3.6.2 Implementing std::fmt::Display for your own types

3.7 Exposing your types to the world

3.7.1 Protecting private data

3.8 Creating In-line Documentation

3.8.1 Using rustdoc to Render Docs For a Single Source File