2 Rust’s basic building blocks

 

This chapter covers

  • Exploring the core Rust patterns
  • Diving into Rust generics
  • Exploring traits
  • Combining generics and traits
  • Deriving traits automatically

In this chapter, I’ll introduce and discuss some of Rust’s most important abstractions and features, which I call building blocks and which serve as the foundation of nearly all design patterns in Rust. Reviewing and understanding these building blocks before diving deeper into other patterns is crucial. For some readers, this chapter may appear to be a review of language basics; it sets the stage for more advanced topics, however, so I recommend that you don’t skip it.

We’ll begin by discussing generics and traits in Rust. They are the core building blocks of nearly every design pattern in Rust, along with Rust’s pattern matching and functional features (discussed in chapter 3). These elements constitute the meat and potatoes of the language.

2.1 Generics

After you’ve moved beyond basic syntax, generics are likely the first big topic you’ll need to learn. Rust’s generics are compile-time, type-safe abstractions that also enhance metaprogramming; they allow you to use placeholders instead of concrete types in function and structure definitions. Generics (combined with traits, which we’ll discuss in section 2.2) permit type-safe programming in a way that doesn’t require explicit definitions of every possible type.

2.1.1 A Turing-complete type system

2.1.2 Why generics?

2.1.3 Basics of generics

2.1.4 Exploring Rust’s Option

2.1.5 Marker structs and phantom types

2.1.6 Generic parameter trait bounds

2.2 Traits

2.2.1 Why traits are not object-oriented programming

2.2.2 What’s in a trait?

2.2.3 Understanding traits by examining object-oriented code

2.2.4 Combining generics and traits

2.2.5 Deriving traits automatically

2.2.6 Trait objects

Summary

sitemap