chapter four

4 Core Design Patterns

 

This chapter covers

  • Understanding resource acquisition is initialization (RAII)
  • Passing arguments by value vs. reference
  • Constructors
  • Object member visibility and access
  • Error handling
  • Global state handling with lazy-static.rs, OnceCell, and static_init

Now we’re ready to dive into some more concrete patterns. We begin by reviewing some elementary topics: RAII, passing values, constructors, and visibility. Then, we’ll move on to slightly more complex subjects: error handling and global variables. While discussing many different topics in this chapter, we’ll focus on bite-sized patterns, which you’ll find yourself using a lot.

In this chapter, we will also introduce crates, which are Rust libraries built by the community and are a very important part of Rust programming. The Rust language is built on crates; you won’t get far without using them. While it’s possible to go full not-invented-here syndrome and eschew crates entirely, I don’t recommend this. Even the largest, most well-funded organizations rely heavily on open-source software to build their stacks to varying degrees.

4.1 Resource acquisition is initialization (RAII)

4.1.1 Understanding RAII in C and C++

4.1.2 RAII in Rust

4.2 Passing arguments by value vs reference

4.2.1 Passing by value

4.2.2 Passing by reference

4.2.3 When to do what: passing by value versus reference

4.3 Constructors

4.3.1 Constructor arguments

4.4 Object member visibility and access

4.5 Error handling

4.6 Global state

4.6.1 lazy-static.rs

4.6.2 once_cell

4.6.3 static_init

4.6.4 std::cell::OnceCell

4.7 Summary