3 Compound data types

 

This chapter covers

  • Composing data with structs
  • Creating enumerated data types
  • Adding methods and 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 for your project

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. Together, struct and enum can compose other types to create something more useful than what 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. In this chapter, we also discuss how to add methods to types with impl blocks. Lastly, we take a deeper look at traits, Rust’s system for defining interfaces.

3.1 Using plain functions to experiment with an API

3.2 Modeling files with struct

3.3 Adding methods to a struct with impl

3.3.1 Simplifying object creation by implementing new()

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 an 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