liveBook · Manning

Chapter 4: Building your own types

What you will learn in chapter 4 of Learn Rust in a Month of Lunches

Introduces structs and enums as ways to build Rust types and methods as functions attached to those types.

After this chapter you will be able to

What it builds on

Section by section

Introduction

Introduces structs and enums as ways to build Rust types and methods as functions attached to those types.

Key terms: structs, enums, implementing types, methods

4.1 A quick overview of structs and enums

Introduces the distinction between structs and enums using a book’s properties and purchase formats as examples.

Key terms: struct, enum, structs, enums

4.1.1 Structs

This section introduces Rust’s three kinds of structs and shows how to declare and create a named struct.

Key terms: struct, unit struct, tuple struct, named struct, UpperCamelCase, Country, fields, instantiate, population, capital

4.1.2 Enums

This section introduces enums as choices between variants, shows how to name and use variants, and explains that variants can hold data.

Key terms: enum, struct, variant, ::, Climate::Tropical, data, use, import, *

4.1.3 Casting enums into integers

This section explains how data-free enum variants get integer values and how to assign different values to them.

Key terms: enum, variant, cast, compiler

4.1.4 Enums to use multiple types

This section shows how an enum can let one Vec hold values of different underlying types while keeping a single element type.

Key terms: Vec<Number>, enum, variant, u32, i32

4.1.5 Implementing structs and enums

This section shows how impl blocks add behavior to structs and enums, distinguishes methods from associated functions, and introduces Debug derivation and Self versus self.

Key terms: impl, impl block, methods, associated functions, self, ::, &mut self, Debug, {:?}, #[derive(Debug)]

4.2 Destructuring

This section shows how to take values out of a struct with destructuring, including renaming fields, ignoring unwanted fields, and destructuring in a function signature.

Key terms: destructuring, let, struct, destructure, .., signature of a function

4.3 References and the dot operator

This section contrasts explicit dereferencing in comparisons with the automatic dereferencing provided by the dot operator when calling methods, then connects familiar library types to structs and impl blocks.

Key terms: reference, dereferencing, *, dot operator, .is_empty(), dereference, &self, String, Vec, struct

4.4 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 3: More complex types Chapter 5: Generics, option, and result →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.